【发布时间】: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