当前位置: 代码迷 >> JavaScript >> js循环数组各种步骤array-升级版
  详细解决方案

js循环数组各种步骤array-升级版

热度:397   发布时间:2013-11-09 17:06:41.0
js循环数组各种方法array-升级版
var myStringArray = ["Hello","World"];
for (var i = 0; i < myStringArray.length; i++) {
    alert(myStringArray[i]);
    //Do something
}


Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
  alert(array[i]);
}

for(var i in this.$GLOBAL_DETAIL.album_photo_ids){if(this.$GLOBAL_DETAIL.album_photo_ids[i] == "3487675024077108") alert(this.$GLOBAL_DETAIL.album_photo_ids[i]);}


[1,2,3,4].map( function(item) {
     alert(item);
})


var x = [1,2,3,4].map( function(item) { return item * 10; } );

// And now x is [10,20,30,40]


var myStringArray = [ "Hello", "World" ]
var len = myStringArray.length
for (var i=0; i<len; ++i) {
  if (i in myStringArray) {
    var s = myStringArray[i];
    ... do something with s ...
  }
}


var myStringArray = [ "Hello", "World" ]
myStringArray.forEach( function(s) { 
     ... do something with s ...
} )


var i=0,item,items = ['one','two','three'];
while(item=items[i++]){
    console.log(item);
}

// logs: 'one','two','three'

and for the reverse order, an even more efficient loop
var items = ['one','two','three'], i=items.length;
while(i--){
    console.log(items[i]);
}

// logs: 'three','two','one'

or the classical for loop
var items = ['one','two','three']
for(var i=0,l=items.length; i < l ; i++){
    console.log(items[i]);
}

// logs: 'one','two','three'


var myStringArray = ['Hello', 'World']; // array uses [] not {}
for (var i in myStringArray) {
    console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
}
  相关解决方案