[undefined]和[,]之间有什么区别?

时间:2012-08-04 13:11:28

标签: javascript

  

可能重复:
  What is “undefined x 1” in JavaScript?

在Chrome 21中,将[,]提供给控制台输出

  

[undefined x 1]

并提供[undefined]输出

  

[未定义]

[undefined][undefined x 1]之间的区别是什么?

符号[undefined x 1]是什么?

4 个答案:

答案 0 :(得分:11)

[,]sparse array。它的长度为1,但没有值(0 in [,] === false)。它也可以写成new Array(1)

[undefined]是一个长度为1的数组,其值undefined位于索引0

当访问属性“0”时,两者都将返回undefined - 第一个因为未定义该属性,第二个因为该值是“未定义”。但是,数组是不同的,他们的output in the console也是如此。

答案 1 :(得分:5)

[,]创建一个长度为1且没有索引的数组。

[undefined]创建一个长度为1的数组,其索引为undefined 0

Chrome的undefined × x适用于没有顺序索引的稀疏数组:

var a = [];

a[8] = void 0; //set the 8th index to undefined, this will make the array's length to be 9 as specified. The array is sparse
console.log(a) //Logs undefined × 8, undefined, which means there are 8 missing indices and then a value `undefined`

如果你在稀疏数组上使用.forEach,它会跳过不存在的索引。

a.forEach(function() {
    console.log(true); //Only logs one true even though the array's length is 9
});

如果您执行基于.length的正常循环,那么

for (var i = 0; i < a.length; ++i) {
    console.log(true); //will of course log 9 times because it's only .length based
}

如果您希望.forEach的行为与非标准实施相同,那就有问题。

new Array(50).forEach( function() {
    //Not called, the array doesn't have any indices
});

$.each( new Array(50), function() {
    //Typical custom implementation calls this 50 times
});

答案 2 :(得分:0)

在Chrome 21上,我再次向[]输出了[]个奇怪的[a, b, c, ...]

无论如何,是Javascript的数组符号,所以你基本上定义了一个没有值的数组。

但是,结束[,,] > [undefined x2] [1,2,] > [1, 2] [1,2,,] > [1, 2, undefined × 1] [1,2,,,] > [1, 2, undefined × 2] [1,2,,3,4,,,6] > [1, 2, undefined × 1, 3, 4, undefined × 2, 6] 可以使数组生成更容易。那么Chrome告诉你的是数组中有一个未定义的值。有关示例,请参阅代码。

{{1}}

答案 3 :(得分:-1)

看起来它只是显示重复的“未定义”值的简便方法。例如:

> [,,,]
  [ undefined x 3 ]

[][undefined]完全不同。如果我是你,我会仔细检查。