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

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

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


当前回答

JavaScript中的数组遍历作弊表

给定一个数组,可以通过以下多种方式之一遍历它。

1.经典for loop

const myArray=['Hello','World'];for(设i=0;i<myArray.length;i++){console.log(myArray[i]);}

2.用于。。。属于

const myArray=['Hello','World'];for(myArray的常量项){console.log(项);}

3.Array.prototype.forEach()

const myArray=['Hello','World'];myArray.forEach(项=>{console.log(项);});

4.while循环

const myArray=['Hello','World'];设i=0;while(i<myArray.length){console.log(myArray[i]);i++;}

5.do…while循环

const myArray=['Hello','World'];设i=0;做{console.log(myArray[i]);i++;}而(i<myArray.length);

6.队列样式

const myArray=['Hello','World'];while(myArray.length){console.log(myArray.shift());}

7.堆栈样式

注:该列表在本页中以相反的方式打印。const myArray=['Hello','World'];while(myArray.length){console.log(myArray.pop());}

其他回答

这个答案为循环和数组函数提供了一种替代方法,以遍历数组。

在某些情况下,在常规循环和回调上使用递归实现是有意义的。特别是,如果必须使用多个数组或嵌套数组。避免编写嵌套循环来访问多个数组中的数据。我还发现这段代码更容易读写。

/**
  array is the array your wish to iterate. 
  response is what you want to return.
  index increments each time the function calls itself.
**/

const iterateArray = (array = [], response = [], index = 0) => {
    const data = array[index]

    // If this condition is met. The function returns and stops calling itself.
    if (!data) {
      return response
    }
    // Do work...
    response.push("String 1")
    response.push("String 2")

    // Do more work...

    // THE FUNCTION CALLS ITSELF
    iterateArray(data, response, index+=1)
}

const mainFunction = () => {
    const text = ["qwerty", "poiuyt", "zxcvb"]

    // Call the recursive function
    const finalText = iterateArray(text)
    console.log("Final Text: ", finalText()
}

假设传递给iterateArray的数组包含对象而不是字符串。每个对象中都包含另一个数组。您必须运行嵌套循环才能访问内部数组,但如果递归迭代,则不必如此。

您还可以将iterateArray设置为Promise。

const iterateArray = (array = [], response = []) =>
  new Promise(async (resolve, reject) => {
    const data = array.shift()
    // If this condition is met, the function returns and stops calling itself.
    if (!data) {
      return resolve(response)
    }

    // Do work here...

    const apiRequestData = data.innerArray.find((item) => {
      item.id === data.sub_id
    })

    if (apiRequestData) {
      try {
        const axiosResponse = await axios.post(
          "http://example.com",
          apiRequestData
        )
        if (axiosResponse.status === 200) {
          response.push(apiRequestData)
        } else {
          return reject("Data not found")
        }
      } catch (error) {
        reject(error)
      }
    } else {
      return reject("Data not found")
    }
    // THE FUNCTION RESOLVES AND CALLS ITSELF
    resolve(iterateArray(data, response))
  })

在JavaScript中,不建议使用for In循环遍历Array,但最好使用for循环,例如:

for(var i=0, len=myArray.length; i < len; i++){}

它也进行了优化(“缓存”数组长度)。如果你想了解更多,请阅读我关于这个主题的帖子。

JavaScript中有多种循环数组的方法。

通用循环:

var i;
for (i = 0; i < substr.length; ++i) {
    // Do something with `substr[i]`
}

每个ES5:

substr.forEach(function(item) {
    // Do something with `item`
});

jQuery.each:

jQuery.each(substr, function(index, item) {
    // Do something with `item` (or `this` is also `item` if you like)
});

查看此信息以获取详细信息,或者您也可以检查MDN是否在JavaScript中循环遍历数组,并使用jQuery检查每个数组的jQuery。

深奥的

让a=[“你好”,“世界”];while(a.length){console.log(a.shift());}

性能测试

今天(2022-11-13),我在Chrome 107、Safari 15.2和Firefox 106上对选定的解决方案进行了测试。

结论

解决方案C和D在所有阵列的所有浏览器上都是快速或最快的。解决方案A和B在所有阵列的所有浏览器上都是最慢的

后果

细节

我执行3项测试:

small-用于2元素数组(如OP)-可以在此处运行中等-用于10K元素阵列-您可以在这里运行大-对于100K元素数组-您可以在这里运行

下面的代码段显示了测试中使用的代码。

函数A(A){设r=0;而(a.length)r+=a.shift().length;返回r;}函数B(a){设r=0;对于(i in a)r+=a[i]长度;返回r;}函数C(a){设r=0;对于(a的x)r+=x.length;返回r;}函数D(a){设r=0;对于(i=0;i<a.length;++i)r+=a[i].length;返回r;}函数E(a){设r=0;a.对于每个(x=>r+=x.length);返回r;}let arr=[“你好”,“世界!”];[A,B,C,D,E].forEach(f=>console.log(`${f.name}:${f([…arr])}`))

以下是Chrome对于中等阵列的示例结果:

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