Reputation: 2767
I am looking for a way to iterate over an array and only output the first item, and when iterating again, output the second item.
var array = [1,2,3]
iterate : function () {
$.each(array, function(a,b) {
console.log(a); // This will log 1 and 2 and 3
});
This will log 1,2 and 3 but I just want to log 1 first and when the iterate
function is called again, it will log 2 and then 3
I am assigning iterate
function to a button (an increment button). So the increment button will simply output 1 when clicked first, and then 2 when clicked again, and then 3 when clicked again.
Upvotes: 1
Views: 344
Reputation: 10765
Set two const variables to hold your minimum value and your maximum value, and declare a mutable variable for holding your count:
const min = 0;
const max = 4;
let counter = 0;
//function to reduce count if counter greater than min
function ReduceCount(){
if(counter > min)
{
counter--;
}
console.log(counter);
}
//function to increase counter if less than max
function IncreaseCount(){
if(counter < max)
{
counter++;
}
console.log(counter);
}
//Document Ready attach events for button clicks4
$(function(){
//Attach click events
$('#btnIncrease').on('click', function(){
IncreaseCount();
});
$('#btnDecrease').on('click', function(){
DecreaseCount();
});
});
<button type="button" id="btnIncrease">Increase</button>
<button type="button" id="btnDecrease">Decrease</button>
Upvotes: 1
Reputation: 10148
This is how I would've done it
var arr = [1,2,3,4]
var index = 0;
function amClicked(){
console.log(arr[index%arr.length]);
index++
if(index == arr.length){
document.getElementById("yo").disabled = true;
}
}
<input type="button" id="yo" onclick="amClicked()" value="yo" />
Upvotes: 1