数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
当你的数组有很多旧项替换新项时,你可以这样使用:
函数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,“嗨”));
其他回答
这里有一句话。它假设项将在数组中。
var项= [523,3452,334,31,5346] var替换= (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr) 控制台。日志(替换项,3452,1010)
这个就行了
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()属性。
首先,像这样重写数组:
var items = [523,3452,334,31,...5346];
接下来,通过索引号访问数组中的元素。确定索引号的公式为:n-1
要替换数组中的第一项(n=1),写:
items[0] = Enter Your New Number;
在您的示例中,数字3452位于第二个位置(n=2)。所以确定索引号的公式是2-1 = 1。因此,编写下面的代码将3452替换为1010:
items[1] = 1010;
来自@gilly3的回答很棒。
替换数组中的对象,保持数组顺序不变
当我从服务器获取数据时,我更喜欢以下方式将新的更新记录更新到我的记录数组中。它保持秩序完整,相当直截了当的一行。
Users =用户。map(u => u.id !== editedUser。)id吗?u: editedUser);
Var用户= [ {id: 1,姓:'John',姓:'Ken'}, {id: 2,姓:'Robin',姓:'Hood'}, {id: 3,名:“威廉”,姓:“库克”} ]; var editedUser = {id: 2,名字:'Michael',姓:'Angelo'}; Users =用户。map(u => u.id !== editedUser。)id吗?u: editedUser); Console.log ('users -> ', users);
如果使用一个复杂的对象(甚至是一个简单的对象),你可以使用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'