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

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

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

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


当前回答

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

例如:

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

其他回答

最简单的方法是使用一些库,如下划线和映射方法。

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

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]

我建议的解决方案是:

items.splice(1, 1, 1010);

拼接操作将从索引1开始,删除数组中的一项(即3452),并将其替换为新的项1010。

javascript中替换数组元素的函数式方法:

Const replace = (array, index,…items) =>[…数组。Slice (0, index),…项目,…数组。Slice (index + 1)];

这个就行了

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

使用indexOf查找元素。

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