数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
使用indexOf查找元素。
var i = items.indexOf(3452);
items[i] = 1010;
其他回答
使用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']
这个就行了
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, 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'
Array.indexOf()方法将替换第一个实例。获取每个实例使用Array.map():
a = a.map(function(item) { return item == 3452 ? 1010 : item; });
当然,这会创建一个新数组。如果你想在适当的地方做,使用Array.forEach():
a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });
var index = Array.indexOf(Array value);
if (index > -1) {
Array.splice(index, 1);
}
从这里,您可以根据相同的索引从数组中删除特定的值 你可以在数组中插入值。
Array.splice(index, 0, Array value);