1

Consider an array:

var array = ['one', 'two', 'three'];

I need to iterate it and get such alerts:

The 0 value is one

The 1 value is two

The 2 value is three

for ( i=0; i<array.length; i++) {
  alert( 'The ' + ? + 'value is ' + array[i] );
}

How can I do this? Thanks.

4
  • 1
    I'm not sure whether or not you're trolling us =) Commented Aug 30, 2011 at 15:04
  • @jadarnel27 I'm sorry, the question really is not I wanted to be. I simplified it a lot. But because of the answers, now I see, that I have to change script logic, to use nested 'for' loops or something. Thanks to all! Commented Aug 30, 2011 at 15:20
  • I hope I didn't offend. I saw your other (very helpful) answers about javascript / jQuery, and thought you were messing with us =) I get it now. Commented Aug 30, 2011 at 15:23
  • 1
    Don't bother, it's ok :) Commented Aug 30, 2011 at 15:27

4 Answers 4

6

Just use i, it will be the position.

for ( i=0; i<array.length; i++) {
   alert( 'The ' + i + 'value is ' + array[i] );
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to alert the position and is associated value, you will need to use i to indicate the position, and array[i] to indicate value:

//Will output "The 0 value is one", "The 1 value is two", ...

for (var i=0; i<array.length; i++){
  alert( 'The ' + i + 'value is ' + array[i] );
}

7 Comments

You might of misunderstood, I think he wants ? to be i.
That's not even valid JavaScript that you posted. edit: it is now that you've changed the ? to i.
I fixed it, it was a bit of a typo :)
DV removed. I think your brain was moving faster than your hands =)
@Jim, that was part of the typo :)
|
2
var i, max;

for ( i=0, max = array.length; i < max; i += 1) {
   alert( 'The ' + i + 'value is ' + array[i] );
}
  • Declare your vars at the beginning. This help to prevent hoisting.

  • In order to be more efficient, save the array length, so you don't have to query the array object every time.

  • Use i += 1 instead of i++.

Comments

1

Please use a variable to read the length of the array only once.

Also be careful, if you don't use the var statement in front of variables in JavaScript, the parser will look for a variable with the same name up in the chain. If you are using a local variable, always declare it with the var statement.

for ( var i = 0, len = array.length; i < len; i++) {
   alert( 'The ' + i + ' value is ' + array[i] );
}

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.