为什么typeof array [0] =='undefined'不起作用?

时间:2012-12-24 23:04:55

标签: javascript undefined typeof

我想在对它执行操作之前检查数组中的下一个元素是否存在,但我无法检查它是否未定义。例如:

// 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

2 个答案:

答案 0 :(得分:6)

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!");

答案 1 :(得分:0)

使用数组时,在访问数组索引之前,还应检查数组本身。

错误:

if (arr[0] == ...)

好:

if (typeof arr != "undefined" and arr[0]==......
相关问题