替换年龄较大的员工>与年轻员工50岁。
我正在尝试更新我forEach()
数组中的项目。分配current
失败,同时注意index
并在forEach()
阻止工作后替换项目。请解释一下这种行为?
var youngerEmployee = {
name: {
first: 'B',
last: 'C'
},
age: 25
}
var employees = [
{
name: {
first: 'X',
last: 'Y'
},
age: 45
},
{
name: {
first: 'A',
last: 'B'
},
age: 54
}
];
/* --- Failed approach --- */
employees.forEach(
(employee) => {
if(employee.age > 50) {
employee = youngerEmployee;
}
}
);
console.log(employees);
/* --- Successful approach --- */
var i = -1;
employees.forEach(
(employee, index) => {
if(employee.age > 50) {
i = index;
}
}
);
employees[i] = youngerEmployee;
console.log(employees);
答案 0 :(得分:1)
在“失败的方法”中,employees
数组未更改,因为employee
引用了数组中的当前员工。通过分配employee = youngerEmployee
,您可以更改引用,否则employees
数组不会受到影响。
答案 1 :(得分:0)
使用map
代替forEach
它不会操纵原始数组
var youngerEmployee = {
name: {
first: 'B',
last: 'C'
},
age: 25
}
var employees = [{
name: {
first: 'X',
last: 'Y'
},
age: 45
},
{
name: {
first: 'A',
last: 'B'
},
age: 54
}
];
var x = employees.map(function(item) {
if (item.age > 50) {
item = youngerEmployee
}
return item
});
console.log(x)
答案 2 :(得分:0)
当您需要修改某些数组项时,可以使用数组map()
代替forEach()
:
var youngerEmployee = {
name: {
first: 'B',
last: 'C'
},
age: 25
}
var employees = [
{
name: {
first: 'X',
last: 'Y'
},
age: 45
},
{
name: {
first: 'A',
last: 'B'
},
age: 54
}
];
employees = employees.map(
(employee) => {
if(employee.age > 50) {
employee = youngerEmployee;
}
return employee;
}
);
console.log(employees);