我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
如果你想使用 forEach(),它会看起来像 -
theArray.forEach ( element => {
console.log(element);
});
如果你想使用(),它会看起来像 -
for(let idx = 0; idx < theArray.length; idx++){
let element = theArray[idx];
console.log(element);
}
其他回答
现在一个简单的解决方案是使用 underscore.js 图书馆,它提供了许多有用的工具,如每一个,并将自动将工作分配给原住民的Each 如果可用。
一个CodePen的例子,它是如何工作:
var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});
看也
在 for_each...in(MDN)中,它解释说,对于每个(对象变量)是作为ECMA-357(EAX)标准的一部分,而对于(MDN)来说,它描述了使用(对象变量)为(对象变量)作为和谐(ECMAScript 6)提议的一部分的下一个方法。
如果你想通过一系列用箭函数的对象旋转:
let arr = [{name:'john', age:50}, {name:'clark', age:19}, {name:'mohan', age:26}]; arr.forEach((person)=>{ console.log('I am ' + person.name + ' and I am ' + person.age + ' old'); })
你可以使用:
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。
如果你需要一个圆体的工作进行序列(而不是平行),一个等待在圆体将等待承诺安排之前继续。
const a = [“a”,“b”,“c”]; for (let index = a.length - 1; index >= 0; --index) { const element = a[index]; console.log(element); }
(ES2015+) 用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于
Caveat 为主机提供的物品
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]