我正在尝试根据传递给函数的值创建多个 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));