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

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

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

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


当前回答

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

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

其他回答

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

如果你知道它的价值,

items[items.indexOf(334)] = 1010;

如果你想知道这个值是否存在,那么使用,

var point = items.indexOf(334);

if (point !== -1) {
    items[point] = 1010;
}

如果你知道地点(位置),那么直接使用,

items[--position] = 1010;

如果你想替换一些元素,你知道起始位置只意味着,

items.splice(2, 1, 1010, 1220);

有关.splice的更多信息

使用indexOf查找元素。

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

我用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;
};

这个就行了

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()属性。

使用ES6扩展操作符和.slice方法替换列表中元素的不可变方法。

const arr = ['fir', 'next', 'third'], item = 'next'

const nextArr = [
  ...arr.slice(0, arr.indexOf(item)), 
  'second',
  ...arr.slice(arr.indexOf(item) + 1)
]

验证它是否有效

console.log(arr)     // [ 'fir', 'next', 'third' ]
console.log(nextArr) // ['fir', 'second', 'third']