我对map()的行为感到非常困惑。
我有这样一个对象数组:
const products = [{
...,
'productType' = 'premium',
...
}, ...]
我将这个数组传递给一个函数,该函数应返回相同的数组,但其中所有产品都是免费的:
And I'm passing this array to a function that should return the same array but with all product made free:[{
...,
'productType' = 'free',
...
}, ...]
该函数的作用是:
const freeProduct = function(products){
return products.map(x => x.productType = "free")
}
这将返回以下数组:
["free", "free", ...]
所以我重新编写了我的函数,使其变成:
const freeProduct = function(products){
return products.map(x => {x.productType = "free"; return x})
}
虽然这个功能可以按预期返回数组,但这就是我失去理智的时刻,在这两种情况下,我的原始产品数组都被修改了。
有关map()的文档表示它不应该修改原始数组(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)。
我甚至尝试创建数组的克隆,将我的函数变成这样:
const freeProduct = function(products){
p = products.splice()
return p.map(x => {x.productType = "free"; return x})
}
但我仍然得到相同的结果(这开始让我发疯)。
如果有人能为我解释我做错了什么,我将非常感激!
谢谢。
.map()
函数处理其中的元素。 我通常使用这段代码作为内联解决方案,相对于大部分情况下的克隆,它更快捷。由于filter
函数返回一个新的数组,因此不会修改原有数组。 - Asqan.filter(e => e)
只是生成一个新数组,其中 falsey (null
,0
,undefined
,等) 值被删除。Map 也会生成一个新数组,因此,除非您想过滤掉 falsey 值,否则在这里使用 filter 是没有用处的。 - SimpleJ