我有一些具有某些属性的对象数组。我想对对象属性做一些数学运算,并希望也返回一个数组。
我试过了,似乎没有用。
array.map(el => {
el.count * 2;
return el
})
Run Code Online (Sandbox Code Playgroud)
array = [{
count: 4,
string: 'randomstring'
}, {
count: 9,
string: 'randomstring'
}, {
count: 7,
string: 'randomstring'
}, {
count: 12,
string: 'randomstring'
}]
Run Code Online (Sandbox Code Playgroud)
预期
array = [{
count: 8,
string: 'randomstring'
}, {
count: 18,
string: 'randomstring'
}, {
count: 14,
string: 'randomstring'
}, {
count: 24,
string: 'randomstring'
}]
Run Code Online (Sandbox Code Playgroud)
el.count * 2;不会改变el.count您可以为其分配值的值,就像
el.count = el.count * 2;
Run Code Online (Sandbox Code Playgroud)
但这会带来另一个问题。它将更改原始数据。因此最好count使用Spread Operator返回具有修改后属性的新对象
el.count = el.count * 2;
Run Code Online (Sandbox Code Playgroud)
你也可以 Object.assign()
let res = array.map(el => Object.assign({count:el.count*2}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |