[未定义] 和 [,] 有什么区别

What is the difference between [undefined] and [,]?

本文关键字:什么 区别 未定义      更新时间:2023-09-26

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

在 Chrome 21 中,[,]馈送到控制台输出

[未定义 x 1]

和馈送[undefined]输出

[未定义]

[undefined][undefined x 1]有什么区别?

什么是符号[undefined x 1]

[,]是一个

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

[undefined] 是一个长度1数组,其值undefined在索引 0 处。

当访问属性" 0 "时,两者都将返回undefined - 第一个是因为该属性未定义,第二个是因为值是"未定义的"。但是,数组是不同的,它们在控制台中的输出也是如此。

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

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

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
});

很奇怪[]在 Chrome 21 上再次为我输出[]

无论如何[a, b, c, ...]是Javascript的数组表示法,所以你基本上定义了一个没有值的数组。

但是,结束,是可以接受的,以使数组生成更容易。因此,Chrome告诉您的是数组中有一个未定义的值。有关示例,请参阅代码。

[,,]
> [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]

看起来这只是显示重复的"未定义"值的简写方法。 例如:

> [,,,]
  [ undefined x 3 ]

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