2012-12-24 30 views
1

我想检查数组中的下一个元素是否存在,然后对其执行操作,但我无法检查它是否未定义。例如:为什么typeof数组[0] =='undefined'不起作用?

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

怎么样'arr.length'? – mellamokb

+1

检查您的控制台是否有错误! – Mathletics

回答

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

^这。为了扩展非代码的第一行:javascript引擎通过alert(typeof arr'很好,但是因为'arr'不是当前的数组,JavaScript引擎在尝试访问它的元素('[1]'),并停止执行该语句。 – joequincy

+0

@joequincy不,它与数组无关:它是一个ReferenceError(不是失败的属性查找或其他)例如(重新迭代响应示例),在'a = {}; alert(typeof a [1])中没有ReferenceError(因为'a'可以在范围内解析)和'a [1] ''会很高兴地评价为'undefined' – 2012-12-24 23:42:53

+1

具体而言:发生'ReferenceError'是因为JavaScript在'typeof'的逻辑被调用之前试图解引用'arr'来查找'arr [1]'因为' arr'不存在,试图解引用它(这是'[1]'做的)失败。 – Amber

0

使用数组时,你访问一个数组的索引,你也应该检查数组本身之前。

错误:

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

好:

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