I am trying to write a code which displays the sum of number of times each option is selected using an array
However whenever I run this code the array resets all elements to zero after running the code the second time
let arr = [0,0,0,0]
const poll = {
registerNewAnswer: function(a)
{
return prompt(`
Which is your favourite Movie?
0: Toy Story
1: Star Wars
2: Fast & Furious
3: Final Destination
(Write option number)
`);
}
}
let b = poll.registerNewAnswer();
console.log(b);
for(let [i,j] of arr.entries())
{
if (i==b)
{
arr[i]=(arr[i]+1);
};
}
console.log(...arr);
You need to store the entries somewhere, otherwise your first line will always reset arr to zero. I suggest localStorage for this example. Could also be a call out to an API for database storage.
In the code below- it first checks for the existence of the localStorage.arr.
Then, if it is null, it creates an empty array and saves it for next time.
Also, b isn't necessary, you can just add it to the array with arr[].
let arr = localStorage.getItem('arr');
if (!arr) {
arr = [];
localStorage.setItem('arr', arr);
}
const poll = {
registerNewAnswer: function()
{
return prompt(`
Which is your favourite Movie?
0: Toy Story
1: Star Wars
2: Fast & Furious
3: Final Destination
(Write option number)`);
}
}
arr.push(poll.registerNewAnswer());
console.log(poll.registerNewAnswer);
for(let [i,j] of arr.entries())
{
if (i==b)
{
arr[i]=(arr[i]+1);
};
}
console.log(...arr);