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

其他回答

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)

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

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

var array=['hai','hello','how','are','you']$(文档).ready(函数(){$('#clickButton').click(函数(){对于(var i=0;i<array.length;i++){警报(阵列[i])}})})<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js“></script><input id=“clickButton”value=“click Me”type=“button”/><div id=“show”></div>

最好使用顺序for循环:

for (var i = 0; i < myStringArray.length; i++) {
    // Do something
}

Opera、Safari、Firefox和Chrome现在都共享一组增强的Array方法来优化许多常见循环。

您可能不需要所有这些,但它们可能非常有用,或者如果每个浏览器都支持它们,它们就会非常有用。

Mozilla实验室发布了他们和WebKit都使用的算法,因此您可以自己添加它们。

筛选器返回满足某个条件或测试的项目数组。

如果每个数组成员都通过测试,则every返回true。

如果有人通过测试,则返回true。

forEach在每个数组成员上运行一个函数,不返回任何内容。

map类似于forEach,但它返回每个元素的操作结果数组。

这些方法都将一个函数作为其第一个参数,并有一个可选的第二个参数,这是一个对象,当数组成员循环通过该函数时,您希望将其范围强加给数组成员。

忽略它,直到你需要它。

indexOf和lastIndexOf查找与其参数完全匹配的第一个或最后一个元素的适当位置。

(function(){
    var p, ap= Array.prototype, p2={
        filter: function(fun, scope){
            var L= this.length, A= [], i= 0, val;
            if(typeof fun== 'function'){
                while(i< L){
                    if(i in this){
                        val= this[i];
                        if(fun.call(scope, val, i, this)){
                            A[A.length]= val;
                        }
                    }
                    ++i;
                }
            }
            return A;
        },
        every: function(fun, scope){
            var L= this.length, i= 0;
            if(typeof fun== 'function'){
                while(i<L){
                    if(i in this && !fun.call(scope, this[i], i, this))
                        return false;
                    ++i;
                }
                return true;
            }
            return null;
        },
        forEach: function(fun, scope){
            var L= this.length, i= 0;
            if(typeof fun== 'function'){
                while(i< L){
                    if(i in this){
                        fun.call(scope, this[i], i, this);
                    }
                    ++i;
                }
            }
            return this;
        },
        indexOf: function(what, i){
            i= i || 0;
            var L= this.length;
            while(i< L){
                if(this[i]=== what)
                    return i;
                ++i;
            }
            return -1;
        },
        lastIndexOf: function(what, i){
            var L= this.length;
            i= i || L-1;
            if(isNaN(i) || i>= L)
                i= L-1;
            else
                if(i< 0) i += L;
            while(i> -1){
                if(this[i]=== what)
                    return i;
                --i;
            }
            return -1;
        },
        map: function(fun, scope){
            var L= this.length, A= Array(this.length), i= 0, val;
            if(typeof fun== 'function'){
                while(i< L){
                    if(i in this){
                        A[i]= fun.call(scope, this[i], i, this);
                    }
                    ++i;
                }
                return A;
            }
        },
        some: function(fun, scope){
            var i= 0, L= this.length;
            if(typeof fun== 'function'){
                while(i<L){
                    if(i in this && fun.call(scope, this[i], i, this))
                        return true;
                    ++i;
                }
                return false;
            }
        }
    }
    for(p in p2){
        if(!ap[p])
            ap[p]= p2[p];
    }
    return true;
})();