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

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

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

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


当前回答

我建议的解决方案是:

items.splice(1, 1, 1010);

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

其他回答

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

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

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

非常适合简单的交换。试试下面的代码片段

const items =数组(523,3452,334,331,5346); console.log(物品) items[items. indexof (3452)] = 1010 console.log(物品)

当你的数组有很多旧项替换新项时,你可以这样使用:

函数replaceArray(数组,oldItem, newItem) { 对于(设I = 0;I < array.length;我+ +){ const index = array.indexOf(oldItem); If (~index) { array[index] = newItem; } } 返回数组 } console.log(replaceArray([1,2,3,2,2,8,1,9], 2,5)); console.log (replaceArray([1、2、3、2、2、8、1,9],2,“嗨”));

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

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

例如:

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