Anders
Anders

Reputation: 183

For loop in Javascript

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" ?

Upvotes: -1

Views: 73

Answers (3)

php-dev
php-dev

Reputation: 7156

If 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.

Upvotes: 1

erik.j.johnson
erik.j.johnson

Reputation: 191

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();
}

Upvotes: 2

Kami
Kami

Reputation: 19447

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

Upvotes: 6

Related Questions