6

我真的没有看到哪里出了问题。我在 Banks & Porcello 的 O'Reilly 的 Learning React 中看到了这个特定示例的帖子。但是,这些帖子似乎工作正常,但我的例子却没有。如果我有错字,我看不到它。我的缺点在哪里?我不知道为什么我得到一个空字符串值而不是“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>
4

1 回答 1

9
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

于 2017-12-18T09:52:10.073 回答