How to increment a variable on calling a function in javascript? [duplicate]
I'm trying to store the value of i into a.
function sequence(i,a) {
i=a;
if (i==1) {
i++;
return strings[i]
}
else {
i=0;
i++;
a=i;
return strings[i]
}
};
strings is an array where I have stored five objects. When I call the function first time it enters else block, and then it enters else block second time as well. Is there a way to make the value of a=1 in the first attempt, and make it inter the if block.
I also tried declaring i=0 outside the function, and using just i++. But everytime the function is called, i becomes 0.
It would be great if we don't require 2 variables at all and are able to store and increment the value of i.
You can use a closure (basically a function that's returned from another one but that keeps track of the variables in its outer scope without making them global.)
// Simple array
const arr = [1, 2, 3, 4, 5];
// A button and a function that returns a new function
// (the closure) as the listener.
// Pass in the array of things to it
const button = document.querySelector('button');
button.addEventListener('click', handleClick(arr), false);
// The function accepts the array of things,
// and initialises the array count
function handleClick(arr, index = 0) {
// And we return a function that acts as the
// listener when the button is clicked. It increments
// the value until it hits the end of the array, and
// then starts again. The benefit of the closure is that
// it keeps a note of `index` so you don't have to
return function () {
console.log(arr[index]);
if (index === arr.length - 1) {
index = 0;
} else {
index++;
}
}
}
<button>Next</button>