我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
console.log("Index" + index);
console.log("Element" + item);
})
其他回答
Iterators 提高效率,让您同时消耗列表中的物品,就好像它们是流。 使 iterator 特别的是它通过收藏的方式. 其他插槽需要将整个收藏上传到前面,以便在收藏中进行 iterate,而 iterator 只需要知道收藏中的当前位置。
您可以通过呼叫 iterator 的下一个方法访问当前项目,下一个方法将返回当前项目的值,并将一个 boolean 指示您到达收藏结束时。
您也可以使用 Symbol.iterator 将您的常规序列转换为 iterator 如下:
您也可以将您的常规序列转换为这样的 iterator:
注意事项:
对象不默认可用,在这种情况下使用为..in,因为而不是值,它用钥匙工作。
如果你想在一个序列上旋转,请使用标准的三部分旋转。
for (var i = 0; i < myArray.length; i++) {
var arrayItem = myArray[i];
}
您可以通过缓存 myArray.length 或向后转向它获得某些性能优化。
我来自Python,我发现这种方式更清晰。
theArray 是 array,例子是 array 的元素:
for (let instance of theArray)
{
console.log("The instance", instance);
}
或
for (instance in theArray)
{
console.log("The instance", instance);
}
与比较:
theArray.forEach(function(instance) {
console.log(instance);
});
但是,在一天结束时,两人都在做同样的事情。
// 使用前端 ECMAScript 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