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


当前回答

你可以使用:

ForEach theArray.forEach(功能(序列,索引) { console.log(索引); console.log(序列); }; for(var i=0; i<theArray.length; i++) { console.log(i) } 地图 theArray.map(x => console.log(x));地图 theArray.filter(x => console.log(x));

而且还有很多其他人为 iteration。

其他回答

某些 C 风格的语言使用 foreach 通过列表旋转。 在 JavaScript 中,这与 for..in 旋转结构进行:

var index,
    value;
for (index in obj) {
    value = obj[index];
}

要避免通过对象的原型继承的阅读值,只需检查是否属于对象的财产:

for (i in obj) {
    if (obj.hasOwnProperty(i)) {
        //do stuff
    }
}

此外,ECMAScript 5 已添加一个 forEach 方法到 Array.prototype 可以用来列出一个序列,使用一个字符串(多字符串在文件中,所以你仍然可以使用它在更老的浏览器):

arr.forEach(function (val, index, theArray) {
    //do stuff
});

重要的是要注意的是,当通话返回虚假时,Array.prototype.forEach 不会破裂。 jQuery 和 Underscore.js 提供各自的变量,以提供可以短循环的漏洞。

表演

细节

在测试中,我们计算序列元素的总数,我对小序列(10个元素)和大序列(1M元素)进行测试,并将它们分为三个组:

A - 测试B - 测试C - 其他/替代方法

Cross 浏览器结果

所有测试浏览器的结果

浏览器*

配有10个元素

此分類上一篇

配备1000元元素

Chrome 的结果:您可以在这里在您的机器上进行测试

此分類上一篇

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,向我展示了对旋转的好处和恐惧。

根据新更新 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

你可以使用:

ForEach theArray.forEach(功能(序列,索引) { console.log(索引); console.log(序列); }; for(var i=0; i<theArray.length; i++) { console.log(i) } 地图 theArray.map(x => console.log(x));地图 theArray.filter(x => console.log(x));

而且还有很多其他人为 iteration。