数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
javascript中替换数组元素的函数式方法:
Const replace = (array, index,…items) =>[…数组。Slice (0, index),…项目,…数组。Slice (index + 1)];
其他回答
如果使用一个复杂的对象(甚至是一个简单的对象),你可以使用es6, Array.prototype.findIndex是一个很好的选择。对于OP的数组,他们可以这样做,
const index = items.findIndex(x => x === 3452)
items[index] = 1010
对于更复杂的对象,这真的很管用。例如,
const index =
items.findIndex(
x => x.jerseyNumber === 9 && x.school === 'Ohio State'
)
items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'
const items =数组(1,2,3,4,5); console.log(物品) items[items. indexof (2)] = 1010 console.log(物品)
items[items.indexOf(3452)] = 1010
非常适合简单的交换。试试下面的代码片段
const items =数组(523,3452,334,331,5346); console.log(物品) items[items. indexof (3452)] = 1010 console.log(物品)
第一个方法
在一行中替换或更新数组项的最佳方法
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
如果你想要一个简单的糖纸,你可以:
(elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);
如:
let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
const updatedElement = { id: 1, name: 'updated element one' };
如果你没有id,你可以像这样字符串化元素:
(elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);