-1

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

1
  • 5
    Of course. What problem did you encounter while trying to implement what you describe? Commented May 20, 2014 at 21:30

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Just a note. Array.forEach() will not work for IE earlier than IE9
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.