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

其他回答

我还没有看到这种变化,我个人最喜欢这种变化:

给定一个数组:

var someArray = ["some", "example", "array"];

您可以在不访问长度属性的情况下对其进行循环:

for (var i=0, item; item=someArray[i]; i++) {
  // item is "some", then "example", then "array"
  // i is the index of item in the array
  alert("someArray[" + i + "]: " + item);
}

请参阅本JsFidle演示:http://jsfiddle.net/prvzk/

这只适用于非稀疏阵列。这意味着数组中的每个索引实际上都有一个值。然而,我发现在实践中我几乎从未在JavaScript中使用过稀疏数组。。。在这种情况下,通常更容易将对象用作映射/哈希表。如果您有一个稀疏数组,并且希望在0上循环。。length-1,您需要for(vari=0;i<someArray.length;++i)构造,但仍需要在循环内使用if来检查当前索引处的元素是否已实际定义。

此外,正如CMS在下面的注释中所提到的,您只能在不包含任何错误值的数组上使用它。示例中的字符串数组是有效的,但如果您有空字符串或0或NaN等数字,则循环将提前中断。在实践中,这对我来说几乎从来都不是问题,但这是一件需要记住的事情,这使得在使用它之前,这是一个需要考虑的循环……这可能会使某些人失去资格:)

我喜欢这个循环的地方是:

写起来很短无需访问(更不用说缓存)长度属性要访问的项在循环中自动定义你选择的名字下的身体。与array.push和array.please非常自然地结合,使用列表/堆栈等数组

这种方法之所以有效,是因为数组规范规定,当您从索引中读取一个项>=数组长度时,它将返回undefined。当你写到这样的位置时,它实际上会更新长度。

对我来说,这个构造最接近于我喜欢的Java5语法:

for (String item : someArray) {
}

…还有一个额外的好处,那就是了解循环内的当前索引

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

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

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

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

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

var obj = ["one","two","three"];

for(x in obj){
    console.log(obj[x]);
}