小编Poo*_*eas的帖子

使用JavaScript中的新Array()定义未定义的值

看一些javascript代码,我看到(类似)这个:

var arr = Array.apply(null, {length: 10});
Run Code Online (Sandbox Code Playgroud)

阅读Function.prototype.apply()的MDN文档,我了解到虽然它通常期望一个数组作为它的第二个参数,它是要传递给被调用函数的参数数组,

你也可以使用类似于数组的任何类型的对象,所以在实践中这意味着它将具有属性长度和范围内的整数属性(0 ...长度).

所以从我所知道的,它调用Array()好像它传递了10个参数,但由于它没有定义任何这些"整数属性",所以就好像它传递了10个未定义的参数.那是对的吗?

console.log(arr);
Run Code Online (Sandbox Code Playgroud)

产量

[undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]

这与结果完全不同

var barr = new Array(10);
console.log(barr);
Run Code Online (Sandbox Code Playgroud)

是的

[,,,,,,,,,]

这些阵列的行为也不同.

console.log(arr.map(function(item) { return 'hi';}));
console.log(barr.map(function(item) { return 'hi';}));
Run Code Online (Sandbox Code Playgroud)

['hi','hi','hi','hi','hi','hi','hi','hi','hi','hi']

[,,,,,,,,,]

我想知道为什么map函数不能用于第二个.所以我检查了console.log(1 in arr);哪个给了true和`console.log(1 in barr);' 这给了.

所以我目前的猜测是arr是一个数组,它包含10个变量作为整数属性,每个变量的值都是undefined,而barr是一个数组,尽管它的长度为10,但没有整数属性.并且Array.apply可以工作,因为它询问{length:10}它的属性0是什么,接收未定义,因此将undefined分配给它正在构造的数组的属性0,依此类推.我的推理是否正确?是否真的没有那么简单的方法来定义一个数组,该数组包含其范围内每个索引的未定义整数属性,而不是根本没有整数属性?因为看这个,在我看来这new Array()是无用的.

javascript arrays properties

7
推荐指数
1
解决办法
1440
查看次数

标签 统计

arrays ×1

javascript ×1

properties ×1