我想在对它执行操作之前检查数组中的下一个元素是否存在,但我无法检查它是否未定义。例如:
// Variable and array are both undefined
alert(typeof var1); // This works
alert(typeof arr[1]); // This does nothing
var arr = [1,1];
alert(typeof arr[1]); // This works now
最佳答案
alert(typeof arr[1]); // This does nothing
它没有做任何事情,因为它因错误而失败:
ReferenceError: arr is not defined
如果您改用这种方式尝试:
var arr = [];
alert(typeof arr[1]);
然后你会得到你所期望的。但是,进行此检查的更好方法是使用数组的 .length
属性:
// Instead of this...
if(typeof arr[2] == "undefined") alert("No element with index 2!");
// do this:
if(arr.length <= 2) alert("No element with index 2!");
关于javascript - 为什么 typeof array[0] == 'undefined' 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026352/