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


当前回答

jQuery 使用 $.map 的方式:

var data = [1, 2, 3, 4, 5, 6, 7];

var newData = $.map(data, function(element) {
    if (element % 2 == 0) {
        return element;
    }
});

// newData = [2, 4, 6];

其他回答

根据新更新 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. 要停止执行,请使用 Array#some 如下:

[1,2,3].some(function(number) {
    return number === 1;
});

這是因為有些回來是真實的,一旦任何的呼叫回來,執行在順序,回來是真實的,短循環的執行的其他。

var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
    console.log("Index" + index);
    console.log("Element" + item);
})

如果你想在一个序列上旋转,请使用标准的三部分旋转。

for (var i = 0; i < myArray.length; i++) {
    var arrayItem = myArray[i];
}

您可以通过缓存 myArray.length 或向后转向它获得某些性能优化。

一个 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
  }
);