这个数组真的需要传播语法吗?

时间:2019-01-16 00:26:45

标签: javascript arrays ecmascript-6 spread-syntax

昨天我正在研究这个示例,我想知道这种传播语法(唯一使用的一种)在这种情况下是否有实用程序?鉴于带有对象的数组将完全不会改变;还是我弄错了?如果可以,怎么办?

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);

1 个答案:

答案 0 :(得分:3)

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

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

但是如果您想复制,那么当a为a时,b不会被更改

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