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

Ran*_*lue 8 javascript

可能重复:
JavaScript中的"undefined x 1"是什么?

在Chrome 21中,[,]输入控制台输出

[undefined x 1]

并提供[undefined]输出

[未定义]

[undefined]和之间有什么区别[undefined x 1]

符号是什么[undefined x 1]

Ber*_*rgi 11

[,]是一个稀疏数组.它有一个长度1,但没有值(0 in [,] === false).它也可以写成new Array(1).

[undefined]是一个长度数组,1其值为undefinedindex 0.

当访问属性" 0"时,两者都将返回undefined- 第一个因为没有定义属性,第二个因为值是"未定义".但是,阵列是不同的,控制台中输出也是如此.


Esa*_*ija 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`
Run Code Online (Sandbox Code Playgroud)

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

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

就像你做一个.length基于正常的循环一样:

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

如果您希望.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
});
Run Code Online (Sandbox Code Playgroud)