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


当前回答

ECMAScript 5(JavaScript版本)与Arrays一起工作:

forEach - 通过序列中的每个项目,并与每个项目所需的一切。

['C', 'D', 'E'].forEach(function(element, index) {
  console.log(element + " is #" + (index+1) + " in the musical scale");
});

// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale

在这种情况下,更有兴趣使用一些内置功能在序列上运行。

地图 - 它创建一个新的序列,结果是呼叫回复功能. 这个方法是很好的使用,当你需要格式化的元素的序列。

// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
  return elem.toUpperCase();
});

// Output: ['BOB', 'JOE', 'JEN']

减少 - 正如名称所说,它将序列减少到一个单一值,通过在当前元素中传输的特定函数和以前的执行结果。

[1,2,3,4].reduce(function(previous, current) {
  return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10

每次 - 返回真实或虚假,如果序列中的所有元素在呼叫回复函数中通过测试。

// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];
ages.every(function(elem) {
  return elem >= 18;
});

// Output: false

过滤器 - 非常相似于每一个,除了过滤器返回一个序列的元素返回真实的给定的功能。

// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
  return (elem % 2 == 0)
});

// Output: [2,4,6]

其他回答

在 jQuery 中,有三种实施。

var a = [3,2];

$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3

如果你想使用 forEach(),它会看起来像 -

theArray.forEach ( element => {
    console.log(element);
});

如果你想使用(),它会看起来像 -

for(let idx = 0; idx < theArray.length; idx++){
    let element = theArray[idx];
    console.log(element);
}
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
    console.log("Index" + index);
    console.log("Element" + item);
})

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
}