2012-05-14 173 views
4

现在我该如何检查该值是否定义为未定义,或者如果它未真正定义?
例如。Javascript:将未定义的数组定义值和未定义的数组值定义为

var a = []; 
a[0] = undefined; 

// a defined value that's undefined 
typeof a[0] === "undefined"; 

// and a value that hasn't been defined at all 
typeof a[1] === "undefined"; 

有没有办法分开这两个?可以使用for-in循环遍历数组,但有没有更简单的方法?

+2

未定义意味着它是未定义的 - 如果您明确地将某些内容设置为未定义,那么根据定义,这也是未定义的。您可以使用null,根据数组长度检查索引,等等。 –

+0

是的。我简化了真正的问题,让问题变得更有意义。该数组实际上是一个来自数据的集合,其中undefined是一个有效的值,它告诉我一些未定义的东西。当数组[undefined]出现问题时,问题似乎就出现了,这让我怀疑问题的主题...... – Marcus

回答

2

可以使用in运算符来检查一个给定的指标是数组中存在的,不管其实际价值的

var t = []; 
t[0] = undefined; 
t[5] = "bar"; 

console.log(0 in t); // true 
console.log(5 in t); // true 
console.log(1 in t); // false 
console.log(6 in t); // false 

if(0 in t && t[0] === undefined) { 
    // the value is defined as "undefined" 
} 

if(!(1 in t)) { 
    // the value is not defined at all 
} 
+0

与我的答案相同,但有点解释:) – malko

+0

我没有看到它,我们已经发布与此同时 :) – pomeh

3

,你可以检查,如果指数是在给定的数组:

0 in a // => true 
1 in a // => false