数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
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 index = Array.indexOf(Array value);
if (index > -1) {
Array.splice(index, 1);
}
从这里,您可以根据相同的索引从数组中删除特定的值 你可以在数组中插入值。
Array.splice(index, 0, Array value);
用for循环很容易完成。
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 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()属性。
第一个方法
在一行中替换或更新数组项的最佳方法
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