我正在尝试在 ES6 中对此进行编码。以下是我想要实现的目标。假设我有一个名为schools
.
let schools = [
{name: 'YorkTown', country: 'Spain'},
{name: 'Stanford', country: 'USA'},
{name: 'Gymnasium Achern', country: 'Germany'}
];
现在,我想编写一个名为的函数,该函数editSchoolName
将接受 3 个参数schools
(这是我在上面定义的数组)oldName
和name
.
我将在参数中传递学校的名称,oldName
并且该名称应使用参数中的值进行更新name
。
我不想更改变量的状态,schools
所以我使用了一个map
函数,它将返回一个包含更改的新数组。
该editSchoolName
函数将像这样调用 -
var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
在这里, nameYorkTown
应该替换为 name New Gen
。所以数组的期望值updatedSchools
应该是 -
let updatedSchools = [
{name: 'New Gen', country: 'Spain'},
{name: 'Stanford', country: 'USA'},
{name: 'Gymnasium Achern', country: 'Germany'}
];
这就是我的 editSchoolName 函数的样子 -
const editSchoolName = (schools, oldName, name) =>
schools.map(item => {
if (item.name === oldName) {
/* This is the part where I need the logic */
} else {
return item;
}
});
在更改editSchoolName
功能以实现上述预期结果时需要帮助。