在我之前有关使用map()的一篇文章中,使用标准if / else块解决了该问题。但是现在我有另一个问题。这是使用if / else的解决方案:

<!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>Transforming Data</title>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
  <h1>Transforming Data</h1>
  <p>Open the console</p>

  <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: newName
          }
        }
        else {
          return item
        }
      });

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

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

  </script>

</body>
</html>


但是,使用功能箭头时不想为我工作。映射时不会进行替换。但是,我使用的是相同的解决方案-即:“名称:名称”。我究竟做错了什么?

<!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>Transforming Data</title>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
  <h1>Transforming Data</h1>
  <p>Open the console</p>

  <script type="text/babel">

    let schools = [
      'Yorktown',
      'Stratford',
      'Washington & Lee',
      'Wakefield'
    ];

    const editName = (oldName, name, arr) =>
      arr.map(item => (item.name === oldName) ?
        ({...item, name: name}) :
        item
      );

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

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

  </script>

</body>
</html>

最佳答案

您的新数组是字符串数组,而不是对象数组,因此没有name属性,这意味着item.name将始终返回undefined。

如果要继续使用字符串数组,则必须像下面这样修改函数:



    let schools = [
      'Yorktown',
      'Stratford',
      'Washington & Lee',
      'Wakefield'
    ];

    const editName = (oldName, name, arr) =>
      arr.map(item => (item === oldName) ? name : item);

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

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

09-25 17:48
查看更多