这段代码会产生一个新数组var list = [
{ id: 1, name: “a” },
{ id: 2, name: “b” },
{ id: 3, name: “c” }
];var replacement = { id: 2, name: “b”, sex: “female” };
list = list.map(t => { return t.id === replacement.id
? replacement
: t;
});console.log(list);
如果你想直接在原数据中替换,用 for 循环……这个你应该会写吧
var list = [
{ id: 1, name: “a” },
{ id: 2, name: “b” },
{ id: 3, name: “c” }
];var replacement = { id: 2, name: “b”, sex: “female” };for (let i = 0, len = list.length; i
if (list[i].id === replacement.id) {
list[i] = replacement;
}
}console.log(list);