数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
第一个方法
在一行中替换或更新数组项的最佳方法
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
其他回答
替换可以在一行中完成:
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(项目);
这个就行了
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()属性。
下面是一个可重用函数的基本答案:
function arrayFindReplace(array, findValue, replaceValue){
while(array.indexOf(findValue) !== -1){
let index = array.indexOf(findValue);
array[index] = replaceValue;
}
}
var items = Array(523,3452,334,31,5346);
如果你知道它的价值,
items[items.indexOf(334)] = 1010;
如果你想知道这个值是否存在,那么使用,
var point = items.indexOf(334);
if (point !== -1) {
items[point] = 1010;
}
如果你知道地点(位置),那么直接使用,
items[--position] = 1010;
如果你想替换一些元素,你知道起始位置只意味着,
items.splice(2, 1, 1010, 1220);
有关.splice的更多信息
如果有人对如何从数组的下标替换一个对象感兴趣,这里有一个解决方案。
通过id查找对象的索引:
const index = items.map(item => item.id).indexOf(objectId)
使用object .assign()方法替换该对象:
Object.assign(items[index], newValue)