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

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

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


当前回答

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

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

/**
  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))
  })

其他回答

嗯,这个怎么样:

for (var key in myStringArray) {
    console.log(myStringArray[key]);
}

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

我强烈建议使用Undercore.js库。它为您提供了可用于迭代数组/集合的各种函数。

例如:

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...

是的,您可以使用循环在JavaScript中执行同样的操作,但不限于此。在JavaScript中有很多方法可以对数组进行循环。假设下面有一个数组,您想对其进行循环:

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

以下是解决方案:

1) For循环

for循环是JavaScript中循环数组的常见方式,但它不被认为是大型数组的最快解决方案:

for (var i=0, l=arr.length; i<l; i++) {
  console.log(arr[i]);
}

2) While循环

while循环被认为是循环长数组的最快方式,但在JavaScript代码中通常很少使用:

let i=0;

while (arr.length>i) {
    console.log(arr[i]);
    i++;
}

3) 做的同时do-while与while执行相同的操作,但语法差异如下:

let i=0;
do {
  console.log(arr[i]);
  i++;
}
while (arr.length>i);

这些是实现JavaScript循环的主要方法,但还有其他几种方法可以实现。

此外,我们还使用for in循环对JavaScript中的对象进行循环。

还可以查看JavaScript中Array上的map()、filter()、reduce()等函数。他们做事情可能比使用while和for更快、更好。

如果您想进一步了解JavaScript中的异步函数和数组,这是一篇很好的文章。

函数式编程在当今世界的发展。有充分的理由:功能性技术可以帮助您编写更容易编写的声明性代码一目了然地理解、重构和测试。函数式编程的基石之一是它的特殊用途列表和列表操作。这些东西正是听起来就像是:一系列的东西,以及你对它们做的事情。但功能思维方式对待他们的方式与你有点不同可能会想到。本文将详细介绍我喜欢称之为“大三个“列表操作:map、filter和reduce围绕这三个功能是实现编写干净的功能代码功能和反应式编程的强大技术。这也意味着你再也不用编写for循环了。

阅读更多>>此处:

使用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