数组中的每一项都是一个数字:

var items = Array(523,3452,334,31, ...5346);

如何用新物品替换旧物品?

例如,我们想用1010替换3452,该怎么做呢?


当前回答

Array.indexOf()方法将替换第一个实例。获取每个实例使用Array.map():

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

当然,这会创建一个新数组。如果你想在适当的地方做,使用Array.forEach():

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

其他回答

var index = Array.indexOf(Array value);
        if (index > -1) {
          Array.splice(index, 1);
        }

从这里,您可以根据相同的索引从数组中删除特定的值 你可以在数组中插入值。

 Array.splice(index, 0, Array value);

用for循环很容易完成。

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;

使用indexOf查找元素。

var i = items.indexOf(3452);
items[i] = 1010;

ES6道:

const items = Array(523, 3452, 334, 31, ...5346);

我们想用1010替换3452,解决方案:

const newItems = items.map(item => item === 3452 ? 1010 : item);

当然,这个问题是很多年前的问题了,现在我更喜欢使用不可变的解决方案,当然,这对ReactJS来说是很棒的。

为了经常使用,我提供以下功能:

const itemReplacer = (array, oldItem, newItem) =>
  array.map(item => item === oldItem ? newItem : item);

如果使用一个复杂的对象(甚至是一个简单的对象),你可以使用es6, Array.prototype.findIndex是一个很好的选择。对于OP的数组,他们可以这样做,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

对于更复杂的对象,这真的很管用。例如,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'