开发者

How to get array element number?

开发者 https://www.devze.com 2023-04-01 13:41 出处:网络
Consider an array: var array = [\'one\', \'two\', \'three\']; I need to iterate it and get such al开发者_JAVA百科erts:

Consider an array:

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

I need to iterate it and get such al开发者_JAVA百科erts:

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.


Just use i, it will be the position.

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


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


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


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] );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消