Js为每个循环更改数组内的对象 [英] Js change object inside array in for each loop

查看:797
本文介绍了Js为每个循环更改数组内的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改每个循环中的当前对象并且它不起作用,为什么它不起作用,我该怎么做?

I want to change the current object in for each loop and it does not work, Why it is not working and how can i do this?

var arr = [{num: 1}, {num: 2}];

arr.forEach(function(item) {
  item = {somethingElse: 1}
});

console.log(arr);


推荐答案

它没有用,因为你所做的只是更新您给出的参数的值( item ),它没有与数组的实时连接。一旦您的回调返回,该更改就会消失。

It's not working because all you're doing is updating the value of the argument you were given (item), which doesn't have a live connection to the array. That change disappears as soon as your callback returns.

最合适的方法是使用 map

The most appropriate way to do this is to use map:

var arr = [{num: 1}, {num: 2}];

arr = arr.map(function(item) {
  return {somethingElse: 1};
});

console.log(arr);

map 为每个项目和构建提供功能来自你返回的任何数组。

map gives your function each item and builds a new array from whatever you return.

如果你在原地更新阵列而不是建立一个新阵列很重要,你可以使用 forEach ,你只需要分配回你正在更新的数组元素。 forEach 的回调的第二个参数是您正在访问的索引,因此:

If it's important that you update the array in-place instead of building a new one, you can use forEach, you just have to assign back to the array element you're updating. The second argument to forEach's callback is the index you're visiting, so:

var arr = [{num: 1}, {num: 2}];

arr.forEach(function(item, index) {
  arr[index] = {somethingElse: 1};
});

console.log(arr);






当然,在上述两种情况下,你都是' d实际上是使用 item 来表示你不在你的示例代码中...如果你想在 item <上添加/删除属性/ code>,而不是完全替换该对象, Cyril的回答向您展示了如何做到这一点。


Of course, in both cases above, you'd actually be using item for something, which you aren't in your example code... If you wanted to add/remove properties on item, not replace the object entirely, Cyril's answer shows you how to do that.

这篇关于Js为每个循环更改数组内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆