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

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

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

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


当前回答

使用indexOf查找元素。

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

其他回答

这个就行了

Array.prototype.replace = function(a, b) {
    return this.map(item => item == a ? b : item)
}

用法:

let items = ['hi', 'hi', 'hello', 'hi', 'hello', 'hello', 'hi']
console.log(items.replace('hello', 'hi'))

输出:

['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']

好处是,每个数组都有.replace()属性。

您可以使用索引编辑列表中的任意数量

例如:

items[0] = 5;
items[5] = 100;

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

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

第一个方法

在一行中替换或更新数组项的最佳方法

array.splice(array.indexOf(valueToReplace), 1, newValue)

Eg:

let items = ['JS', 'PHP', 'RUBY'];

let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')

console.log(replacedItem) //['RUBY']
console.log(items) //['JS', 'PHP', 'PYTHON']

第二种方法

另一种简单的方法是:

items[items.indexOf(oldValue)] = newValue

我用for循环解决了这个问题,遍历原始数组,并将匹配arreas的位置添加到另一个数组,然后遍历该数组,并在原始数组中更改它,然后返回它,我使用了一个箭头函数,但一个常规函数也可以工作。

var replace = (arr, replaceThis, WithThis) => {
    if (!Array.isArray(arr)) throw new RangeError("Error");
    var itemSpots = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == replaceThis) itemSpots.push(i);
    }

    for (var i = 0; i < itemSpots.length; i++) {
        arr[itemSpots[i]] = WithThis;
    }

    return arr;
};