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

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

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


当前回答

考虑一下:

const ITEMS = ['One','Two','Three']
let item=-1

//Then, you get looping with every call of:

ITEMS[item=item==ITEMS.length-1?0:item+1]

其他回答

阵列迭代有4种方式:

// 1: for

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

// 2: forEach

arr.forEach((v, i) => console.log(v));

// 3: for in

for (let i in arr) {
  console.log(arr[i]);
}

// 4: for of

for (const v of arr) {
  console.log(v);
}

总结:1和3个解决方案创建额外的变量,2-创建额外的函数上下文。最好的方式是第四位-“for of”。

最优雅快捷的方式

var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
    value + 1
}

http://jsperf.com/native-loop-performance/8


编辑(因为我错了)


比较循环遍历100000个项目数组的方法,并每次使用新值执行最小操作。

http://jsben.ch/#/BQhED

准备工作:

<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script>
    Benchmark.prototype.setup = function() {
        // Fake function with minimal action on the value
        var tmp = 0;
        var process = function(value) {
            tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
        };
        
        // Declare the test Array
        var arr = [];
        for (var i = 0; i < 100000; i++)
            arr[i] = i;
    };
</script>

测验:

<a href="http://jsperf.com/native-loop-performance/16" 
   title="http://jsperf.com/native-loop-performance/16"
><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>

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

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

/**
  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中执行同样的操作,但不限于此。在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循环了。

阅读更多>>此处:

有几种方法可以在JavaScript中实现。前两个示例是JavaScript示例。第三个使用JavaScript库,即jQuery使用.each()函数。

var myStringArray=[“hello”,“World”];for(myStringArray中的var i){alert(myStringArray[i]);}

var myStringArray=[“hello”,“World”];for(var i=0;i<myStringArray.length;i++){alert(myStringArray[i]);}

var myStringArray=[“hello”,“World”];$.each(myStringArray,函数(索引,值){警报(值);})<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script>