为什么.map将Array(x)与[... Array(x)]区别对待? [英] Why does .map treat Array(x) differently from [...Array(x)]?

查看:58
本文介绍了为什么.map将Array(x)与[... Array(x)]区别对待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是, Array(5) [... Array(5)] 有什么区别?请参见下面的变量 c d 相同,但 .map 对待它的方式有所不同.

The question is, what is the difference between Array(5) and [...Array(5)] See below variable c and d is the same yet .map treats it differently.

let a = [...Array(5)].map((k,i)=>{
  console.log("Hello");
  return i;
})
console.log(a);

let b = Array(5).map((k,i)=>{
  console.log("Hello");
  return i;
})
console.log(b);

let c = Array(5)
let d = [...Array(5)]
console.log(c) // c and d seem to be the same
console.log(d)

推荐答案

因为当您直接调用 Array(5)时,它将创建一个空数组,而不是具有5个 undefined .这就是为什么当您调用map时什么也没有发生的原因,因为它没有迭代的必要,因此它会立即返回.

Because when you directly call Array(5), it creates an empty array, not an array with 5 undefined. This is why nothing happens when you call map because there is nothing for it to iterate over, so it immediately returns.

如果传递给Array构造函数的唯一参数是0到232-1(含)之间的整数,则将返回一个新的JavaScript数组,其length属性设置为该数字(注意:这意味着arrayLength空插槽数组,而不是具有实际未定义值的广告位).如果参数为其他任何数字,则会引发RangeError异常.

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). If the argument is any other number, a RangeError exception is thrown.

请参阅: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Array

这篇关于为什么.map将Array(x)与[... Array(x)]区别对待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆