我正在使用 js 进行调整,我想知道是否有一种方法可以在一个映射迭代中映射的数组中添加另一个元素,然后使该值由映射处理。
示例:
const array1 = [1, 4, 9, 16];
// Pass a function to map
var oneIter = true;
const map1 = array1.map((x) => {
if (oneIter) {
oneIter = false;
array1.push(10);
}
return x * 2
});
console.log(array1);
console.log(map1);
// Expected output: Array [2, 8, 18, 32, 100], Actual output: Array [2, 8, 18, 32]
感谢您的宝贵时间。
尝试通过在 js map 迭代期间简单地推送元素来添加元素。
最佳答案
来自 MDN 的 .map()
:
The map() method is a copying method. It does not alter this. However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:
callbackFn will not visit any elements added beyond the array's initial length when the call to map() began. Changes to already-visited indexes do not cause callbackFn to be invoked on them again. If an existing, yet-unvisited element of the array is changed by callbackFn, its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are not visited.
对于 .forEach()
来说也是如此,我认为对于所有其他数组方法也是如此。
还有一个警告:
Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
映射数组元素通常应该是纯粹的,没有副作用。所以这可能就是数组方法在执行过程中不支持动态长度的原因之一。
使用 for
循环进行突变逻辑。
如果您无论如何都想使用.map()
,只需在第一次迭代后进行额外的映射即可:
const array1 = [1, 4, 9, 16];
let cb = (x, idx) => (idx || array1.push(10) && (cb = x => x * 2), x * 2);
const map1 = array1.map(cb);
map1.push(...array1.slice(map1.length).map(cb));
console.log(...array1);
console.log(...map1);
使用Array::reduce()
:
const array1 = [1, 4, 9, 16];
let cb = (x, idx) => (idx || array1.push(10) && (cb = x => x * 2), x * 2);
const [map1] = array1.reduce(([arr, len], item, idx) =>
(arr.push(cb(item, idx), ...(idx === len - 1 ? array1.slice(len).map(cb) : [])), [arr,len]), [[],array1.length])
console.log(...array1);
console.log(...map1);
关于javascript - Js 在其中添加 map 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77117215/