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

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

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


当前回答

您可以使用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。

其他回答

如果您正在使用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,即使它是简单的字符串或数字值。)该方法返回其第一个参数,迭代的对象。

在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()

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)

如果有人对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()方法是最慢的近似方法,可能是函数调用开销的结果。

它不是100%相同,但相似:

var myStringArray=['Hello','World'];//数组使用[]而不是{}for(myStringArray中的var i){console.log(i+'->'+myStringArray[i]);//我是索引/键,而不是项目}