javascript 如何检查JS中是否设置了多维数组项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16883473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:21:25  来源:igfitidea点击:

How to check if a multidimensional array item is set in JS?

javascriptarraysmultidimensional-arrayisset

提问by Colargol

How to check if a multidimensional array item is set in JS?

如何检查JS中是否设置了多维数组项?

w[1][2] = new Array;
w[1][2][1] = new Array;
w[1][2][1][1] = 10; w[1][2][1][2] = 20; w[1][2][1][4] = 30;

How to check if w[1][2][1][3]is set?

如何检查是否w[1][2][1][3]设置?

Solution with if (typeof w[1][2][1][3] != 'undefined')doesn't work.

解决方案if (typeof w[1][2][1][3] != 'undefined')不起作用。

I don't want to use an Object instead of Array.

我不想使用对象而不是数组。

采纳答案by Patrick Evans

You are not checking the previous array elements existence before checking its children as the children elements cant exist if the parent doesnt

在检查其子元素之前,您没有检查先前的数组元素是否存在,因为如果父元素不存在,则子元素将不存在

if( 
    typeof(w) != 'undefined' &&
    typeof(w[1]) != 'undefined' &&
    typeof(w[1][2]) != 'undefined' &&
    typeof(w[1][2][1]) != 'undefined' &&
    typeof(w[1][2][1][3]) != 'undefined' &&
  ) {
    //do your code here if it exists  
  } else {
    //One of the array elements does not exist
  }

The if will run the code in the elseclause if it sees any of the previous elements not existing. It stops checking the others if any of the preceding checks returns false.

else如果它看到任何不存在的先前元素,则 if 将运行子句中的代码。如果任何前面的检查返回 false,它就会停止检查其他的。

回答by basilikum

Here is a more generic way you can do it by extending the prototype of Array:

这是一种更通用的方法,您可以通过扩展 的原型来实现Array

Array.prototype.check = function() {
    var arr = this, i, max_i;
    for (i = 0, max_i = arguments.length; i < max_i; i++) {
        arr = arr[arguments[i]];
        if (arr === undefined) {
            return false;
        }
    }
    return true;    
}

w.check(1, 2, 1, 4); //will be true if w[1][2][1][4] exists

or if you don't like prototype extension you could use a separate function:

或者如果你不喜欢原型扩展,你可以使用一个单独的函数:

function check(arr) {
    var i, max_i;
    for (i = 1, max_i = arguments.length; i < max_i; i++) {
        arr = arr[arguments[i]];
        if (arr === undefined) {
            return false;
        }
    }
    return true;
}

check(w, 1, 2, 1, 4); //will be true if w[1][2][1][4] exists