我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
我會說,為 / 是走的路:
const arr = ['a', 'b', 'c']; for (const v of arr) { console.log(v); // 打印“a”,“b”,“c” }
例如,如果您设置 arr.foo = 'test', for (var v in arr) 将通过 'foo' 密钥旋转. 不同于 forEach(), for/of 不会错过'洞' 在 序列. const arr = ['a', 'c'] 是有效的 JavaScript, 只有 2 个元素是'洞'. 序列功能相当于 ['a', undefined, 'c'].
您可以在此博客中阅读更多关于 for/of vs forEach( )的文章。
其他回答
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);
});
如果您想保持代码的功能,请使用地图:
theArray.map(instance => do_something);
在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。
如果你想在一个序列上旋转,请使用标准的三部分旋转。
for (var i = 0; i < myArray.length; i++) {
var arrayItem = myArray[i];
}
您可以通过缓存 myArray.length 或向后转向它获得某些性能优化。
如果你不关心空白:
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];