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

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

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


当前回答

考虑一下:

const ITEMS = ['One','Two','Three']
let item=-1

//Then, you get looping with every call of:

ITEMS[item=item==ITEMS.length-1?0:item+1]

其他回答

有一种方法可以只迭代自己的对象财产,而不包括原型的属性:

for (var i in array) if (array.hasOwnProperty(i)) {
    // Do something with array[i]
}

但它仍将迭代自定义的财产。

在JavaScript中,任何自定义属性都可以分配给任何对象,包括数组。

如果要在稀疏数组上迭代,应使用for(var i=0;i<array.length;i++)If(i in array)或array.forEach with es5shim。

三个主要选项:

对于(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迭代

如果有人对Array迭代可用的多种机制的性能方面感兴趣,我准备了以下JSPerf测试:

https://jsperf.com/fastest-array-iterator

结果:

传统的for()迭代器是迄今为止最快的方法,尤其是在缓存数组长度时。

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // Do something
}

Array.prototype.forEach()和Array.prototype.map()方法是最慢的近似方法,可能是函数调用开销的结果。

6种不同的方法循环遍历阵列

可以通过许多不同的方法循环遍历数组。我从上到下整理了我最喜欢的6种方法。

1.使用for循环

当它只是在数组中循环时,for循环是我的首选。

让数组=[1,2,3,4,5];for(设i=0;i<array.length;i++){console.log(array[i]);}

2.使用forEach循环

forEach循环是一种在数组中循环的现代方式。此外,它还提供了对阵列和元素的更多灵活性和控制。

让数组=[1,2,3,4,5];array.forEach((元素)=>{console.log(元素);});

3.用于。。。属于

对于of循环允许您直接访问数组元素。

让数组=[1,2,3,4,5];for(数组的let元素){console.log(元素);}

4.用于。。。在回路中

对于中提供了一个键,您可以使用该键访问数组元素。

让数组=[1,2,3,4,5];for(数组中的let索引){console.log(array[index]);}

5.使用while循环

而loop也可以用于循环通过阵列。

让数组=[1,2,3,4,5];let length=array.length;而(长度>0){console.log(array[array.length-length]);长度--;}

6.使用do…while循环

同样,我使用do…while循环

让数组=[1,2,3,4,5];let length=array.length;做{console.log(array[array.length-length]);长度--;}而(长度>0)

在JavaScript中以函数编程方式循环数组的一些用例:

1.只需循环遍历数组

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

注意:严格来说,Array.prototype.forEach()不是一种函数方式,因为它作为输入参数的函数不应该返回值,因此不能将其视为纯函数。

2.检查数组中的任何元素是否通过测试

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3.转换为新阵列

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

注意:map()方法使用对调用数组中的每个元素调用所提供函数的结果创建一个新数组。

4.总结某一特定属性,并计算其平均值

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5.基于原始数组创建新数组,但不进行修改

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6.统计每个类别的数量

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7.基于特定条件检索数组的子集

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

注意:filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

8.对数组进行排序

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

9.在数组中查找元素

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

方法返回数组中满足所提供测试函数的第一个元素的值。

工具书类

Array.prototype.some()Array.prototype.forEach()Array.prototype.map()Array.prototype.filter()Array.prototype.sort()Spread语法Array.prototype.find()