JavaScript:为什么这两个看似等效的程序的控制台输出略有不同?

时间:2017-09-27 22:07:57

标签: javascript

这个程序:

(101) [undefined × 100, "foo"]

输出:

var arr = [];
for(var i = 0; i < 101; i++) {
arr[i] = (i === 100 ? "foo" : undefined);
}
console.log(arr);

然而,这个程序:

"foo"

输出(当然最终有(101) [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined…] ):

@urls

我可能会挑剔,但我只是想确定,为什么输出会有所不同?两个阵列不应该相同吗?

在Chrome版本58中运行。

1 个答案:

答案 0 :(得分:6)

他们并不等同。

第一个是稀疏的,只有一个成员在索引100。第二个成员有101个成员,其中大部分是值undefined

稀疏数组是成员少于.length建议的数组。因此,如果你有一个数组.length101并且所有索引都有一个值,那么它并不稀疏,但如果有&#34;空洞&#34;在缺少实际索引/值的地方,它是一个稀疏数组。

要检查数组是否稀疏,您可以将其.length.length结果的Object.keys进行比较。

var isSparse = arr.length !== Object.keys(arr).length;

要检查是否实际定义了单个成员,请使用in运算符:3 in arr.hasOwnProperty()方法:arr.hasOwnProperty(3)