英文:
Calling Image constructor on map returns an array of empty object
问题
我尝试使用map在另一个数组上创建HtmlImageElement数组。
const foo = Array(5).map(() => new Image())
然后我得到了一个充满空对象的数组。
为什么会这样?
谢谢!
编辑:
看起来在map中构建的任何对象都会出现这种情况。
英文:
I tried to create an array of HtmlImageElement using a map on an other array.
const foo = Array(5).map(() => new Image())
And I got an array full of empty object
Why is that ?
Thanks !
Edit :
It looks like it is the case with any object constructed in a map
答案1
得分: 0
从文档中:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array
arrayLength 如果传递给Array构造函数的唯一参数是一个介于0和2^32 - 1(包括在内)之间的整数,则返回一个新的JavaScript数组,其length属性设置为该数字(注意:这意味着一个arrayLength为空的数组,而不是具有实际undefined值的数组槽位 — 请参阅稀疏数组)。
更多关于稀疏数组的解释在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays
英文:
From the doc : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array
> arrayLength If the only argument passed to the Array constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values — see sparse arrays).
More explanation on sparse arrays here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays
答案2
得分: 0
Array(5) 创建一个新的长度为 5 的空数组,其中所有项都是 undefined。在这个空数组上调用 map() 不会对回调函数产生任何影响(不会被执行)。
要解决这个问题,你可以尝试使用 Array.from(),如下所示:
const foo = Array.from({length:5}, () => new Image());
console.log(foo);
英文:
Array(5) creates a new empty array of a length 5 with all the items as undefined. Calling map() on this empty array has no effect on the callback function (will not be executed).
To solve the issue, you can try Array.from() like following way:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const foo = Array.from({length:5}, () => new Image());
console.log(foo);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。




评论