这个数组真的需要传播语法吗?
does this array really need the 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]
我昨天正在研究这个例子,我想知道这种传播语法(唯一使用的语法)在这种情况下是否有用?鉴于带有对象的数组不会随之改变;或者我错了?如果是,怎么会这样?
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]