javascript - 为什么 new Array(3) 函数不返回数组中的 3 个未定义值?

标签 javascript reactjs ecmascript-6 map-function

<分区>

我正在尝试根据传递给函数的值创建多个 div 标签。 ISo 在我创建一个 new Array(x) 的函数中执行此操作,据推测它应该创建一个包含 x 个未定义指针的数组。但是 console.log(theArray)。它显示 [empty * x] 而不是 undefined 3 次。

myFunction(value){
let myArray=new Array(value).map((_,key) => <div key={key}> Hi There</div>)
return myArray;

在上面的函数中,假设如果我传递 value =3,我希望 myArray 包含 3 个具有 Hi There 值的 div 标签。 相反,它返回 [empty *3]。

请告诉我这是为什么?

最佳答案

如果您通过查看 polyfill 查看 Array.prototype.map 是如何在后台实现的,您会看到在迭代期间检查迭代索引调用映射回调之前的给定数组。

因此对于只有未定义值的数组,检查给定数组中的索引返回 false:

console.log(0 in [, , ]); // prints false

console.log(0 in [1, 2, 3]); //prints true

因此,不满足索引的 if 条件并且您提供的回调永远不会执行,因此您将返回一个包含 len 个未定义值的新数组。

这是 map polyfill 中的代码片段:

//k is the index
k = 0;
//len is the length of the array
while (k < len) {

      var kValue, mappedValue;
      //O is the array and this condition will be false
      if (k in O) { 

        kValue = O[k];
        //your callback will be called here
        mappedValue = callback.call(T, kValue, k, O);
        //a new array is populated with the mapped value and returned
        A[k] = mappedValue;
      }
      k++;
}

可以找到 Array.prototype.map polyfill here .

为防止这种情况,您可以使用 Array.prototype.fill 在调用 map 之前用一个值填充数组:

function myFunction(value){
  let myArray = new Array(value).fill(0).map((_,key) => `<div key={key}> Hi There</div>`);
  return myArray;
}
console.log(myFunction(3));

关于javascript - 为什么 new Array(3) 函数不返回数组中的 3 个未定义值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944429/

相关文章:

javascript - jQuery 方法选择整个页面的内容

尝试读取 .xlsx excel 文件时出现 java.lang.NoSuchMethodError

reactjs - 如何知道是否所有 setState 更新都已应用于 React 组件中的状态?

javascript - 将 'Const' ReactJs 组件转换为基于参数的类

reactjs - 镭安装与 react 17.0.2一起使用时出错

javascript - 访问回调 array.prototype 中的参数

javascript - 替换原型(prototype) : class static getters, 或类字段中的值?

javascript - 每个都打破下划线

javascript - 淡化背景颜色变化动画滞后并减慢

javascript - 如何使用 Javascript 根据另一个数组的相应元素的属性对数组进行排序?