gpt4 book ai didi

javascript - 映射和拼接给出空而不是空

转载 作者:行者123 更新时间:2023-11-29 10:29:03 24 4
gpt4 key购买 nike

我有一个算法:

let someArray = [1, 2, 3, 4, 5]
let mapped = someArray.map(number => {
let index = someArray.indexOf(5)
if (index !== -1) {
someArray.splice(index, 1)
}
console.log(typeof number)
return number
})
console.log(mapped)
console.log(mapped.length)
console.log(Object.keys(mapped).length)

所以我期望的是 mapped=[1,2,3,4]mapped.length=4

但是我有 mapped=[1,2,3,4,empty]mapped.length=5

所以我的想法是:一开始, map 将进行 5 次迭代,所以无论如何它都会这样做。这就是我添加 console.log(typeof number) 的原因。

但是只执行了4次。

我知道要得到我预期的结果,过滤器要好得多。我只是想知道,这里发生了什么?

最佳答案

参见 MDN documentation :

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

If existing elements of the array are changed, their value as passed to callback will be the value at the time map visits them. Elements that are deleted after the call to map begins and before being visited are not visited.

您在遍历数组时改变数组,这意味着一旦达到索引 [4],该元素(其值曾经为 5)不再存在,这意味着该函数不再存在在该迭代中被调用,导致 <empty> .生成的数组由 5 个元素创建,但永远不会对最后一个元素调用回调。

使用 filter相反。

关于javascript - 映射和拼接给出空而不是空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51078427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com