【问题标题】:does this array really need the spread syntax?这个数组真的需要扩展语法吗?
【发布时间】:2019-06-10 01:11:54
【问题描述】:

我昨天正在研究这个例子,我想知道这种扩展语法(唯一使用的)在这种情况下是否有任何实用性?鉴于带有对象的数组根本不会改变;还是我错了?如果有,怎么会?

const quiz = [{
    name: "Superman",
    realName: "Clark Kent"
  },
  {
    name: "Wonderwoman",
    realName: "Dianna Prince"
  },
  {
    name: "Batman",
    realName: "Bruce Wayne"
  },
];

const game = {
  start(quiz) {

    //    ----> this \/
    this.questions = [...quiz];
    this.score = 0;
    // main game loop
    for (const question of this.questions) {
      this.question = question;
      this.ask();
    }
    // end of main game loop
    this.gameOver();
  },
  ask() {
    const question = `What is ${this.question.name}'s real name?`;
    const response = prompt(question);
    this.check(response);
  },
  check(response) {
    const answer = this.question.realName;
    if (response === answer) {
      alert('Correct!');
      this.score++;
    } else {
      alert(`Wrong! The correct answer was ${answer}`);
    }
  },
  gameOver() {
    alert(`Game Over, you scored ${this.score} point${this.score !== 1 ? 's' : ''}`);
  }
}

game.start(quiz);

【问题讨论】:

  • 它需要一个数组的浅拷贝。在此特定代码中没有必要,但通常最好不要改变已传递给函数的数组和/或对象,除非该函数的特定意图是执行该突变。
  • 看起来他只是将quiz的元素散布到一个新数组中
  • @GrzegorzMiśkiewicz 他正在使用模板字符串,将 ` 替换为 ' 会破坏代码
  • 我的错误 - 抱歉。
  • 为了完整性:您不需要扩展语法来克隆数组。您也可以使用arr.slice()Array.from(arr)

标签: javascript arrays ecmascript-6 spread-syntax


【解决方案1】:

您在这里看到的是数组的复制。基本上JS就是这样做的

a = [1,2,3];
b = a;
a.push(4);
// a == b == [1,2,3,4]

但是如果你想制作一个副本,那么当你需要做传播时,b 不会改变

a = [1,2,3];
b = [...a];
a.push(4);
// a == [1,2,3,4], b == [1,2,3]

【讨论】:

    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多