一次遍历 Javascript 数组多个元素的惯用方法是什么?
What is the idiomatic way to loop over a Javascript array multiple elements at a time?
在Python中,您可以进行以下操作:
>>> foo = ["some", "random", "list", "foo"]
>>> for a, b, c in zip(foo, foo[1:], foo[2:]):
... print(f"{a} {b} {c}")
...
some random list
random list foo
如何在 Javascript 中做同样的事情而不用在循环中使用位置索引?或者这是惯用的方式?
你可以拿一台发电机去拿零件。
function* zip(array, n) {
let i = 0;
while (i + n <= array.length) {
yield array.slice(i, i + n);
i++;
}
}
let foo = ["some", "random", "list", "foo"];
for (let [a, b, c] of zip(foo, 3))
console.log(a, b, c);
在Python中,您可以进行以下操作:
>>> foo = ["some", "random", "list", "foo"]
>>> for a, b, c in zip(foo, foo[1:], foo[2:]):
... print(f"{a} {b} {c}")
...
some random list
random list foo
如何在 Javascript 中做同样的事情而不用在循环中使用位置索引?或者这是惯用的方式?
你可以拿一台发电机去拿零件。
function* zip(array, n) {
let i = 0;
while (i + n <= array.length) {
yield array.slice(i, i + n);
i++;
}
}
let foo = ["some", "random", "list", "foo"];
for (let [a, b, c] of zip(foo, 3))
console.log(a, b, c);