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

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

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

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


当前回答

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

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

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

其他回答

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

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

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

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

这个就行了

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

替换可以在一行中完成:

var items =数组(523,3452,334,331,5346); 项目(项目。Map ((e, i) => [i, e])。Filter (e => e[1] == 3452)[0][0]] = 1010 console.log(项目);

或者创建一个函数来重用:

Array.prototype.replace =函数(t, v) { 如果(this.indexOf (t) != 1) 这个(这个。Map ((e, i) => [i, e])。Filter (e => e[1] == t)[0][0]] = v; }; / /检查 var items =数组(523,3452,334,331,5346); 物品。替换(3452、1010); console.log(项目);

使用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']