I am facing a problem: I want the array to save the x value each time the button is clicked.
So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]
<button id="me">Click me to print form E to Z</button>
<script type="text/javascript">
const insertOptions = x=>{
console.log(x);
}
const circleInsertOptions = () => {
let myArray = [];
let x = 48;
myArray.push(48);
console.log(myArray);
return myArray;
};
document.getElementById('me').addEventListener('click', circleInsertOptions);
</script>
I am facing a problem: I want the array to save the x value each time the button is clicked.
So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]
<button id="me">Click me to print form E to Z</button>
<script type="text/javascript">
const insertOptions = x=>{
console.log(x);
}
const circleInsertOptions = () => {
let myArray = [];
let x = 48;
myArray.push(48);
console.log(myArray);
return myArray;
};
document.getElementById('me').addEventListener('click', circleInsertOptions);
</script>
Share
Improve this question
edited Feb 20, 2020 at 2:13
Shark Lasers
4717 silver badges15 bronze badges
asked Feb 19, 2020 at 21:14
Kyle TechKyle Tech
617 bronze badges
3 Answers
Reset to default 7The myArray
variable is local to the function. Each time the function is called, it is initialized with a new array.
If you want to define the array once then you need to define it once and not every time the function is called (i.e. outside the function).
You need to initialize the array outside of the function, otherwise every time you call the function, it will be reset to []
<script type="text/javascript">
let myArray = []; // create array here
const insertOptions = x=>{
console.log(x);
}
const circleInsertOptions = () => {
let x = 48;
myArray.push(48);
console.log(myArray);
return myArray;
};
document.getElementById('me').addEventListener('click', circleInsertOptions);
</script>
let myArray = []; // ARRAY STORED ONCE AS GLOBAL.
const insertOptions = x=>{
console.log(x);
};
const circleInsertOptions = () => {
let x = 48;
myArray.push(48);
console.log(myArray);
return myArray;
};
document.getElementById('me').addEventListener('click', circleInsertOptions);