I have a question about destructuring. I want to change values inside an array. In the below code my instructor did it correctly by using simple code. I want to do the same thing using destructuring.
'use strict'
//intructer code
const poll = {
question: "What is your favourite programming language?",
options: ["0: JavaScript", "1: Python", "2: Rust", "3: C++"],
// This generates [0, 0, 0, 0]. More in the next section!
answers: new Array(4).fill(0),
registerNewAnswer() {
// Get answer
const answer = Number(
prompt(
`${this.question}\n${this.options.join('\n')}\n(Write option number)`
)
);
// Register answer
typeof answer === 'number' &&
answer < this.answers.length &&
this.answers[answer]++;
console.log(this.answers)
},
};
document.querySelector('.poll').addEventListener('click',poll.registerNewAnswer.bind(poll));
Is there are any other ways to do the same thing using restructuring. Below is the code I tried. But I couldn’t change the answers
array values.
//my code
'use strict'
const poll = {
question: "What is your favourite programming language?",
options: ["0: JavaScript", "1: Python", "2: Rust", "3: C++"],
// This generates [0, 0, 0, 0]. More in the next section!
answers: new Array(4).fill(0),
registerNewAnswer() {
// Get answer
const answer = Number(
prompt(
`${this.question}\n${this.options.join('\n')}\n(Write option number)`
)
);
// Register answer
let [w,x,y,z] = this.answers;
switch(answer){
case 0:
w += 1;
break;
case 1:
x += 1;
break;
case 2:
y += 1;
break;
case 3:
z += 1;
}
console.log(w,x,y,z);
console.log(this.answers)
},
};
document.querySelector('.poll').addEventListener('click',poll.registerNewAnswer.bind(poll));