gpt4 book ai didi

javascript - 为什么我的带有扩展语法的 map() 不起作用?

转载 作者:行者123 更新时间:2023-11-30 07:53:10 25 4
gpt4 key购买 nike

我不确定这是哪里出了问题。我在 O'Reilly 的 Learning React 中看到了关于这个具体示例的几篇文章,作者是 Banks 和 Porcello。但是,这些帖子似乎可以正常运行,但我的示例却没有。我没有注意到错别字。我的缺陷的根源是什么?我不确定为什么我得到“HB Woodlawn”而不是空字符串值。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>

<script type="text/babel">

// Editing one object in an array of objects

let schools = [
{name: 'Yorktown'},
{name: 'Stratford'},
{name: 'Washington & Lee'},
{name: 'Wakefield'}
];

const editName = (oldName, newName, arr) =>
arr.map(item => {
if (item.name === oldName) {
return {
...item,
name
}
}
else {
return item
}
});

let updatedSchools = editName('Stratford', 'HB Woodlawn', schools);

console.log(updatedSchools[1]); // name: ""
console.log(schools[1]); // name: "Stratford"

</script>

</body>
</html>

最佳答案

let schools = [
{name: 'Yorktown'},
{name: 'Stratford'},
{name: 'Washington & Lee'},
{name: 'Wakefield'}
];

const editName = (oldName, newName, arr) =>
arr.map(item => {
if (item.name === oldName) {
return {
...item,
name: newName
}
}
else {
return item
}
});

let updatedSchools = editName('Stratford', 'HB Woodlawn', schools);

console.log(updatedSchools[1]); // name: ""
console.log(schools[1]); // name: "Stratford"

您没有为名称添加新值,而是将其留空。添加了name:newName

关于javascript - 为什么我的带有扩展语法的 map() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com