javascript中有没有什么方法可以修改数组值。我已经通过使用 for 循环
完成了此操作,并且还有另一个方法调用 forEach
。我想只用一根线来完成它。就像我看到过使用 Array.prototype.slice 将 onject 转换为数组的代码一样。那么我们是否可以通过使用类似的功能来完成需求。我用谷歌搜索但没有找到任何相关帖子。
this.gome = (function(data){
for(var i=0;i<data.length;i++){
data[i].id = i
}
return data })(data.gome);
this.gome = Array.prototype.slice.call(data.gome,//code) // something like that.
最佳答案
map
是你的 friend 吗:
this.gome = data.gome.map((x, i) => ({...x, id: i}));
或者没有 ES2016 :
this.gome = data.gome.map((x, i) => Object.assign({}, x, {id: i }));
关于javascript - 不使用循环修改数组内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35180739/