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

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

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


当前回答

三个主要选项:

对于(var i=0;i<xs.length;i++){console.log(xs[i]);}xs.forEach((x,i)=>console.log(x));for(xs的常量x){console.log(x);}

下面是详细的示例。


1.循环顺序:

var myStringArray=[“Hello”,“World”];var arrayLength=myStringArray.length;for(var i=0;i<arrayLength;i++){console.log(myStringArray[i]);//做点什么}

Pros

适用于各种环境可以使用break和continue流控制语句

Cons

过于冗长迫切的容易出现一个错误(有时也称为围栏柱错误)

2.阵列.原型.每个:

ES5规范引入了许多有益的数组方法。其中一个是Array.prototype.forEach,它为我们提供了一种简单的方法来遍历数组:

常量数组=[“一”,“二”,“三”]array.forEach(函数(项,索引){console.log(项,索引);});

在撰写ES5规范发布之时(2009年12月)已近十年,它已被桌面、服务器和移动环境中的几乎所有现代引擎实现,因此使用它们是安全的。

使用ES6箭头函数语法,它更加简洁:

array.forEach(item => console.log(item));

箭头功能也被广泛实现,除非您计划支持古老的平台(例如Internet Explorer 11);你去也很安全。

Pros

非常简短和简洁。声明的

Cons

无法使用中断/继续

通常,您可以通过在迭代数组元素之前过滤数组元素来代替中断命令循环的需要,例如:

array.filter(item => item.condition < 10)
     .forEach(item => console.log(item))

请记住,如果您正在迭代一个数组以从中构建另一个数组,则应该使用map。我见过很多次这种反模式。

反模式:

const numbers = [1,2,3,4,5], doubled = [];

numbers.forEach((n, i) => { doubled[i] = n * 2 });

地图的正确使用情况:

常量=[1,2,3,4,5];常量doubled=numbers.map(n=>n*2);console.log(加倍);

此外,如果您试图将数组缩减为一个值,例如,您希望对一个数字数组求和,则应使用reduce方法。

反模式:

const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });

正确使用reduce:

常量=[1,2,3,4,5];常量sum=数字。减少((total,n)=>total+n,0);console.log(总和);

3.声明的ES6:

ES6标准引入了可迭代对象的概念,并定义了用于遍历数据的新构造,即for。。。声明。

此语句适用于任何类型的可迭代对象,也适用于生成器(任何具有\[Symbol.iiterator\]属性的对象)。

根据定义,数组对象是ES6中内置的可迭代对象,因此可以对它们使用以下语句:

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Pros

它可以遍历大量对象。可以使用正常的流量控制语句(中断/继续)。用于迭代串行异步值。

Cons

如果您的目标是较旧的浏览器,则转译的输出可能会让您大吃一惊。

不用于。。。在里面

@zipcodeman建议使用for。。。在语句中,但对于迭代数组,应该避免for-in,该语句旨在枚举对象财产。

它不应用于类似数组的对象,因为:

迭代的顺序没有保证;数组索引不能按数字顺序访问。还枚举了继承的财产。

第二点是它会给您带来很多问题,例如,如果您扩展Array.prototype对象以在其中包含一个方法,那么该属性也会被枚举。

例如:

Array.prototype.foo=“foo!”;var数组=[‘a’,‘b’,‘c’];for(数组中的变量i){console.log(array[i]);}

上面的代码将控制台日志“a”、“b”、“c”和“foo!”。

如果您使用一些严重依赖原生原型扩充的库(如MooTools),这可能是一个特别的问题。

如前所述,for-in语句用于枚举对象财产,例如:

变量obj={“a”:1,“b”:2,“c”:3};for(obj中的var属性){if(obj.hasOwnProperty(prop)){//或如果(Object.protype.hasOwnProperty.call(obj,prop))安全。。。console.log(“prop:”+prop+“value:”+obj[prop])}}

在上面的示例中,hasOwnProperty方法允许您仅枚举自己的财产。就是这样,只有对象物理上具有的财产,没有继承的财产。

我建议您阅读以下文章:

枚举VS迭代

其他回答

例如,我在Firefox控制台中使用了:

[].forEach.call(document.getElementsByTagName('pre'), function(e){ 
   console.log(e);
})

您可以使用querySelectorAll获得相同的结果

document.querySelectorAll('pre').forEach((e)=>{console.log(e.textContent);})<pre>文本1</pre><pre>文本2</pre><pre>文本3</pre>

如果你想用一种简洁的方式写一个快速循环,你可以反过来迭代:

for (var i=myArray.length;i--;){
  var item=myArray[i];
}

这样做的好处是缓存长度(类似于for(var i=0,len=myArray.length;i<len;++i),而不像for(var i=0;i<myArray.long;++i)),同时输入的字符更少。

甚至有些时候,您应该反向迭代,例如在实时NodeList上迭代时,您计划在迭代期间从DOM中删除项。

当然,这是低效的,很多人都鄙视它,但它是最接近上述的一种:

var myStringArray = ["Hello","World"];
myStringArray.forEach(function(f){
    // Do something
})

我认为最好的方法是使用Array.forEach函数。如果你不能使用,我建议从MDN获得polyfill。为了使其可用,在JavaScript中迭代数组当然是最安全的方法。

Array.prototype.forEach()

正如其他人所建议的,这几乎总是你想要的:

var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
numbers.forEach(function(n){
  sum += n;
});

这样可以确保在处理数组的范围内所需的任何内容都保持在该范围内,并且您只处理数组的值,而不处理对象财产和其他成员,这是为了。。在中。

在大多数情况下,对循环使用常规的C样式。只需记住,循环中的所有内容都与程序的其他部分共享其作用域,{}不会创建新的作用域。

因此:

var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];

for(var i = 0; i<numbers.length; ++i){
  sum += numbers[i];
}

alert(i);

将输出“11”-这可能是或可能不是您想要的。

jsFiddle示例:https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/

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