为什么JavaScript数组映射函数没有';是否对数组返回的结果执行(n)?
我只是想更清楚地了解map函数的工作原理以及数组(n)方法为什么JavaScript数组映射函数没有';是否对数组返回的结果执行(n)?,javascript,arrays,Javascript,Arrays,我只是想更清楚地了解map函数的工作原理以及数组(n)方法 对于相关性,让我们选取两个变量bucket和basket 现在,如上所示,当检查bucket和basket是否为数组时,它们都返回true,但是map方法不会对bucket变量执行,而对basket执行 现在让我们使用数组(n)方法和创建一个新变量newBucket。。。扩展运算符 但是,map函数现在为newBucket执行,并且仍然是一个有效数组 任何人都可以在这方面指导我或分享相关链接或指出相同的材料 谢谢你, 沙拉特 大
- 对于相关性,让我们选取两个变量bucket和basket
- 现在让我们使用数组(n)方法和创建一个新变量newBucket。。。扩展运算符
大多数数组迭代方法都不会对从未赋值的元素调用回调。对于刚通过
新建数组(3)
创建的数组元素,情况就是这样
可以使用
.fill()
方法初始化新数组的所有元素。当您使用扩展语法时,将注意未初始化的元素,因此您将得到另一个新数组,其中元素显式初始化为未定义,这不是因为您使用的是react,所以这是一个与react相关的问题。谢谢您的详细解释,非常准确。
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.
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.