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

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

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

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


当前回答

const items =数组(1,2,3,4,5); console.log(物品) items[items. indexof (2)] = 1010 console.log(物品)

其他回答

如果使用一个复杂的对象(甚至是一个简单的对象),你可以使用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'

下面是一个可重用函数的基本答案:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}

来自@gilly3的回答很棒。

替换数组中的对象,保持数组顺序不变

当我从服务器获取数据时,我更喜欢以下方式将新的更新记录更新到我的记录数组中。它保持秩序完整,相当直截了当的一行。

Users =用户。map(u => u.id !== editedUser。)id吗?u: editedUser);

Var用户= [ {id: 1,姓:'John',姓:'Ken'}, {id: 2,姓:'Robin',姓:'Hood'}, {id: 3,名:“威廉”,姓:“库克”} ]; var editedUser = {id: 2,名字:'Michael',姓:'Angelo'}; Users =用户。map(u => u.id !== editedUser。)id吗?u: editedUser); Console.log ('users -> ', users);

使用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);