I have this code:
newsArray = ["John"," Lisa"," Carl"];
And this code in a button event click:
for (var i = 0; i <newsArray.length; i++){
alert("Name: " + newsArray[i]);
}
The code now output "Name: John" "Name: Lisa" "Name: Carl"
Is it possible that second time i click the button, it will only show "Lisa" and "Carl" ?
-
5Of course. What problem did you encounter while trying to implement what you describe?cookie monster– cookie monster2014年05月20日 21:30:57 +00:00Commented May 20, 2014 at 21:30
3 Answers 3
You need to expand the code to set a variable that indicates this is second request.
Expand your code to the following.
var start = 0;
for (var i = start; i <newsArray.length; i++){
alert("Name: " + newsArray[i]);
}
if (start == 0) start++; // increment start if this is the first time
answered May 20, 2014 at 21:32
Kami
19.5k4 gold badges53 silver badges65 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can remove the first element of an array with the shift() method. This is destructive, but would do the job:
function clickHandler() {
newsArray.forEach(function (name) { console.log(name); });
newsArray.shift();
}
answered May 20, 2014 at 21:36
erik.j.johnson
1911 silver badge4 bronze badges
1 Comment
Ramy Nasr
Just a note.
Array.forEach() will not work for IE earlier than IE9If you don't want to keep array values, you can use array shift method.
newsArray = ["John"," Lisa"," Carl"];
for (var i = 0; i <newsArray.length; i++){
alert("Name: " + newsArray[i]);
}
newsArray.shift();
Hope it helps.
answered May 20, 2014 at 21:36
php-dev
7,1864 gold badges27 silver badges39 bronze badges
Comments
lang-js