我只是想更清楚地了解map函数的工作原理以及Array(n(方法。
- 对于相关性,让我们采用两个变量桶和篮子。
var bucket = Array(3); // Create an empty array of length of 3.
console.log(bucket); // Console shows > [null, null, null]
bucket.map((bucketItem, index)=>{ // Trying to run map method over bucket array
console.log(index, bucketItem); // Does not enter this scope.
});
var basket = [null, null, null]; // Create an empty array of length of 3.
console.log(basket); // Console shows > [null, null, null]
basket.map((basketItem, index)=>{ // Trying to run map method over basket array
console.log(index, basketItem); // Console shows > 0 null, 1 null, 2 null
});
console.log(Array.isArray(bucket)) // Console shows > true, stating bucket is an array.
console.log(Array.isArray(basket)) // Console shows > true, stating basket is an array.
现在如上所示,当检查为数组时,存储桶和篮子都返回 true,但是map方法不会对桶变量执行,而对篮子执行。
- 现在让我们使用Array(n(方法创建一个新的变量newBucket和 ...点差运算符。
var newBucket = [...Array(3)]; // Create an empty array of length of 3 and use it with spread opertor.
console.log(newBucket); // Console shows > [null, null, null]
newBucket.map((newBucketItem, index)=>{ // Trying to run map method over newBucket array
console.log(index, newBucketItem); // Console shows > 0 undefined, 1 undefined, 2 undefined
});
console.log(Array.isArray(newBucket)) // Console shows > true, stating newBucket is an array.
但是,映射函数现在为 newBucket 执行,并且newBucket仍然是一个有效的数组。
任何人都可以在这方面指导我或分享相关链接或指出相同的材料吗?
谢谢你, 沙拉特
这是代码的链接
大多数 Array 迭代方法不会为从未赋值的元素调用回调。刚刚通过new Array(3)
创建的数组元素就是这种情况。
可以使用.fill()
方法来初始化新数组的所有元素。当您使用扩展语法时,这将注意未初始化的元素,因此您最终会得到另一个新数组,其中元素显式初始化为undefined
。