我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
如果你想使用 forEach(),它会看起来像 -
theArray.forEach ( element => {
console.log(element);
});
如果你想使用(),它会看起来像 -
for(let idx = 0; idx < theArray.length; idx++){
let element = theArray[idx];
console.log(element);
}
其他回答
没有内置的能力打破 forEach. 要停止执行,请使用 Array#some 如下:
[1,2,3].some(function(number) {
return number === 1;
});
這是因為有些回來是真實的,一旦任何的呼叫回來,執行在順序,回來是真實的,短循環的執行的其他。
如果你需要一个圆体的工作进行序列(而不是平行),一个等待在圆体将等待承诺安排之前继续。
const a = [“a”,“b”,“c”]; for (let index = a.length - 1; index >= 0; --index) { const element = a[index]; console.log(element); }
(ES2015+) 用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于
Caveat 为主机提供的物品
你可以使用:
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。
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);
});
最接近您的想法的方式将是使用 Array.forEach() 接受关闭函数,该函数将适用于序列的每个元素。
myArray.forEach(
(item) => {
// Do something
console.log(item);
}
);
另一种可行的方式是使用 Array.map() 以相同的方式工作,但它也需要所有值,你返回并返回它们在一个新的序列(基本上将每个元素地图到一个新的),如下:
var myArray = [1, 2, 3];
myArray = myArray.map(
(item) => {
return item + 1;
}
);
console.log(myArray); // [2, 3, 4]