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

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

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


当前回答

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

其他回答

我还没有看到这种变化,我个人最喜欢这种变化:

给定一个数组:

var someArray = ["some", "example", "array"];

您可以在不访问长度属性的情况下对其进行循环:

for (var i=0, item; item=someArray[i]; i++) {
  // item is "some", then "example", then "array"
  // i is the index of item in the array
  alert("someArray[" + i + "]: " + item);
}

请参阅本JsFidle演示:http://jsfiddle.net/prvzk/

这只适用于非稀疏阵列。这意味着数组中的每个索引实际上都有一个值。然而,我发现在实践中我几乎从未在JavaScript中使用过稀疏数组。。。在这种情况下,通常更容易将对象用作映射/哈希表。如果您有一个稀疏数组,并且希望在0上循环。。length-1,您需要for(vari=0;i<someArray.length;++i)构造,但仍需要在循环内使用if来检查当前索引处的元素是否已实际定义。

此外,正如CMS在下面的注释中所提到的,您只能在不包含任何错误值的数组上使用它。示例中的字符串数组是有效的,但如果您有空字符串或0或NaN等数字,则循环将提前中断。在实践中,这对我来说几乎从来都不是问题,但这是一件需要记住的事情,这使得在使用它之前,这是一个需要考虑的循环……这可能会使某些人失去资格:)

我喜欢这个循环的地方是:

写起来很短无需访问(更不用说缓存)长度属性要访问的项在循环中自动定义你选择的名字下的身体。与array.push和array.please非常自然地结合,使用列表/堆栈等数组

这种方法之所以有效,是因为数组规范规定,当您从索引中读取一个项>=数组长度时,它将返回undefined。当你写到这样的位置时,它实际上会更新长度。

对我来说,这个构造最接近于我喜欢的Java5语法:

for (String item : someArray) {
}

…还有一个额外的好处,那就是了解循环内的当前索引

使用while循环。。。

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

它记录:“一”、“二”和“三”

对于相反的顺序,一个更有效的循环:

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

它记录:“三”、“二”和“一”

或者经典的for循环:

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

它记录:“一”、“两”、“三”

参考资料:谷歌闭包:如何不编写JavaScript

简单的单线解决方案:

arr=[“桌子”,“椅子”];//解决方案arr.map((e)=>{控制台日志(e);返回e;});

您可以使用map,这是一种函数式编程技术,也可以在Python和Haskell等其他语言中使用。

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

一般语法为:

array.map(func)

一般来说,func需要一个参数,这是数组的一个项。但在JavaScript的情况下,它可以接受第二个参数,即项目的索引,以及第三个参数,也就是数组本身。

array.map的返回值是另一个数组,因此可以这样使用:

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

现在x是[10,20,30,40]。

您不必内联编写函数。它可能是一个单独的功能。

var item_processor = function(item) {
      // Do something complicated to an item
}

new_list = my_list.map(item_processor);

这相当于:

 for (item in my_list) {item_processor(item);}

除非你没有得到new_list。

var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
    console.log(i,j);
}

干净多了。。。