在Java中,可以使用for循环遍历数组中的对象,如下所示:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

我可以在JavaScript中做同样的事情吗?


当前回答

有一种方法可以在循环中的隐式作用域很小的情况下实现,并去掉额外的变量。

var i = 0,
     item;

// Note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
    item; // This is the string at the index.
}

或者如果你真的想得到id并有一个真正经典的for循环:

var i = 0,
    len = myStringArray.length; // Cache the length

for ( ; i < len ; i++ ){
    myStringArray[i]; // Don't use this if you plan on changing the length of the array
}

现代浏览器都支持Array原型上的Each、map、reduce、filter等迭代器方法。

其他回答

var array=['hai','hello','how','are','you']$(文档).ready(函数(){$('#clickButton').click(函数(){对于(var i=0;i<array.length;i++){警报(阵列[i])}})})<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js“></script><input id=“clickButton”value=“click Me”type=“button”/><div id=“show”></div>

正式的(也许是旧的)方式是Array.protocol.forEach(…):

var arr = ["apple", "banana", "cherry", "mango"];
arr.forEach(function(item, index, _) {
   console.log("[" + index + "] = '" + item + "'");
});

我强烈建议使用Undercore.js库。它为您提供了可用于迭代数组/集合的各种函数。

例如:

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...

如果您正在使用jQuery库,请考虑使用http://api.jquery.com/jQuery.each/

根据文档:

jQuery.each(集合,回调(indexInArray,valueOfElement))返回:对象描述:一个泛型迭代器函数,可用于对对象和数组进行无缝迭代。数组和类数组具有长度属性的对象(例如函数的arguments对象)由数值索引从0到长度-1进行迭代。其他对象包括通过其命名的财产进行迭代。$.each()函数与$(selector).each(用于以独占方式对jQuery对象进行迭代。$.each()函数可以用于迭代任何集合,无论它是map(JavaScript对象)或数组。在数组的情况下回调被传递一个数组索引和一个相应的数组值时间(该值也可以通过this关键字访问,但是Javascript将始终将this值包装为Object,即使它是简单的字符串或数字值。)该方法返回其第一个参数,迭代的对象。

Opera、Safari、Firefox和Chrome现在都共享一组增强的Array方法来优化许多常见循环。

您可能不需要所有这些,但它们可能非常有用,或者如果每个浏览器都支持它们,它们就会非常有用。

Mozilla实验室发布了他们和WebKit都使用的算法,因此您可以自己添加它们。

筛选器返回满足某个条件或测试的项目数组。

如果每个数组成员都通过测试,则every返回true。

如果有人通过测试,则返回true。

forEach在每个数组成员上运行一个函数,不返回任何内容。

map类似于forEach,但它返回每个元素的操作结果数组。

这些方法都将一个函数作为其第一个参数,并有一个可选的第二个参数,这是一个对象,当数组成员循环通过该函数时,您希望将其范围强加给数组成员。

忽略它,直到你需要它。

indexOf和lastIndexOf查找与其参数完全匹配的第一个或最后一个元素的适当位置。

(function(){
    var p, ap= Array.prototype, p2={
        filter: function(fun, scope){
            var L= this.length, A= [], i= 0, val;
            if(typeof fun== 'function'){
                while(i< L){
                    if(i in this){
                        val= this[i];
                        if(fun.call(scope, val, i, this)){
                            A[A.length]= val;
                        }
                    }
                    ++i;
                }
            }
            return A;
        },
        every: function(fun, scope){
            var L= this.length, i= 0;
            if(typeof fun== 'function'){
                while(i<L){
                    if(i in this && !fun.call(scope, this[i], i, this))
                        return false;
                    ++i;
                }
                return true;
            }
            return null;
        },
        forEach: function(fun, scope){
            var L= this.length, i= 0;
            if(typeof fun== 'function'){
                while(i< L){
                    if(i in this){
                        fun.call(scope, this[i], i, this);
                    }
                    ++i;
                }
            }
            return this;
        },
        indexOf: function(what, i){
            i= i || 0;
            var L= this.length;
            while(i< L){
                if(this[i]=== what)
                    return i;
                ++i;
            }
            return -1;
        },
        lastIndexOf: function(what, i){
            var L= this.length;
            i= i || L-1;
            if(isNaN(i) || i>= L)
                i= L-1;
            else
                if(i< 0) i += L;
            while(i> -1){
                if(this[i]=== what)
                    return i;
                --i;
            }
            return -1;
        },
        map: function(fun, scope){
            var L= this.length, A= Array(this.length), i= 0, val;
            if(typeof fun== 'function'){
                while(i< L){
                    if(i in this){
                        A[i]= fun.call(scope, this[i], i, this);
                    }
                    ++i;
                }
                return A;
            }
        },
        some: function(fun, scope){
            var i= 0, L= this.length;
            if(typeof fun== 'function'){
                while(i<L){
                    if(i in this && fun.call(scope, this[i], i, this))
                        return true;
                    ++i;
                }
                return false;
            }
        }
    }
    for(p in p2){
        if(!ap[p])
            ap[p]= p2[p];
    }
    return true;
})();