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

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

最佳答案

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

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

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

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

关于javascript - 这个数组真的需要传播语法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54208766/

相关文章:

javascript - 流体布局在 Internet Explorer 7 和 8 中不起作用

javascript - 如何使我的 <h5> 垂直适合父 div?

来自文本文件的java 2D数组

javascript - @syncfusion/ej2-ng-grids 中 GridComponent 的依赖关系解决

javascript - 如何在构造函数中包装使用 Proxy 构造的对象?

javascript - 仅当包含的字符串长度大于 X 时才替换

arrays - 我的程序不会打印数组中第一个和最后一个数字的总和

php - 无法让 PHP 从 mySQL 中提取行条目作为数组

Javascript |最小和最大方法到一种 DRY 方法

javascript - 每页加载的计数计时器从 0 开始