我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
根据新更新 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
其他回答
总结:
创建新序列:地图
let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(元素,索引,序列) => {返回元素 * 2; }) console.log(arr); console.log(newArr);
forEach 是一种位于 Array.prototype 的函数,它将作为一个论点采取呼叫回归函数,然后对序列中的每个元素进行此呼叫回归函数,与地图() 函数不同,forEach 函数不会返回任何东西(未定义)。
一个 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
}
);
如果你不关心空白:
var x;
while(x = y.pop()){
alert(x); //do something
}
x 将包含 y 的最后值,并将从序列中删除。
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];
没有内置的能力打破 forEach. 要停止执行,请使用 Array#some 如下:
[1,2,3].some(function(number) {
return number === 1;
});
這是因為有些回來是真實的,一旦任何的呼叫回來,執行在順序,回來是真實的,短循環的執行的其他。