我如何通过一个序列中的所有输入,使用JavaScript?


当前回答

使用到...可能的地方

async/await support Skips non-numeric props Immutable index
for...of
forEach()
for...in
Regular for

正如上面的表中可以看到的那样,它应该随时随地使用,因为它支持非同步功能,并通过随机修改曲线指数来阻止非数字特性。

合成

const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of nums) {
  /* Do something with num */
}

查看更多例子的参考,链接到规格和与与与与与之间的差异,或者可能检查这个教程,以了解它们如何不同。

其他回答

for (var i = array.length; i--; ) {
     // process array[i]
}


一般来说,对于更高的级别代码,其中清晰度和安全性是更大的担忧,我以前建议使用 Array::forEach 作为您的默认模式的旋转(尽管这些日子我更喜欢使用 for..of)。


for (var i = 0; i < array.length; i++) { ... }   // Forwards

for (var i = array.length; i--; )    { ... }   // Reverse

你会注意到,i--是中间条款(通常我们看到比较),最后条款是空的(通常我们看到i++)。这意味着i--也被用作继续的条件。

如何可以从 array.length 开始而不爆炸? 因为 i-- 运行在每个 iteration 之前,在第一个 iteration 我们将实际上访问项目在 array.length - 1 避免任何问题与 Array-out-of-bounds 未定义的项目. 为什么它不会停止 iterating 之前指数 0? 旋转将停止 iterating 当条件 i-- 评估到虚假值(当它产生 0)。


for (var i = array.length; i --> 0 ;) {

信用去了WYL,向我展示了对旋转的好处和恐惧。

你可以这样打电话给每个人:

forEach 将在您提供的序列上进行 iterate 并为每个 iteration 将有保持该 iteration 的值的元素. 如果您需要索引,您可以通过 i 作为 forEach 的呼叫回复函数中的第二个参数获得当前指数。

Foreach 基本上是一种高顺序函数,它作为其参数需要另一个函数。

let theArray= [1,3,2];

theArray.forEach((element) => {
  // Use the element of the array
  console.log(element)
}

出口:

1
3
2

你也可以在这样的序列上进行 iterate:

for (let i=0; i<theArray.length; i++) {
  console.log(i); // i will have the value of each index
}

一个 forEach 实施(见 jsFiddle):

function forEach(list,callback) {
  var length = list.length;
  for (var n = 0; n < length; n++) {
    callback.call(list[n]);
  }
}

var myArray = ['hello','world'];

forEach(
  myArray,
  function(){
    alert(this); // do something
  }
);

Lambda Syntax 通常不适用于 Internet Explorer 10 或更低版本。

我通常使用

[].forEach.call(arrayName,function(value,index){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

如果您是一个 jQuery 粉丝,并且已经有一个 jQuery 文件运行,您应该逆转指数和值参数的位置。

$("#ul>li").each(function(**index, value**){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

根据新更新 ECMAScript 6 (ES6) 和 ECMAScript 2015 的功能,您可以使用以下选项:

对于洛普

for(var i = 0; i < 5; i++){
  console.log(i);
}

// Output: 0,1,2,3,4

上一篇:在洛普斯

let obj = {"a":1, "b":2}

for(let k in obj){
  console.log(k)
}

// Output: a,b

Array.forEach( )

let array = [1,2,3,4]

array.forEach((x) => {
  console.log(x);
})

// Output: 1,2,3,4

為...LOPS

let array = [1,2,3,4]

for(let x of array){
  console.log(x);
}

// Output: 1,2,3,4

當LOPS

let x = 0

while(x < 5){
  console.log(x)
  x++
}

// Output: 1,2,3,4

此分類上一篇: while loops

let x = 0

do{
  console.log(x)
  x++
}while(x < 5)

// Output: 1,2,3,4