假设我有一个这样的数组:
let arr = [1, 2, 3, 4, 5, 6, "a"]
我怎样才能将它解构为以两个为增量的单个变量?那么 let one = [1, 2]
, let two = [3, 4]
等等?我知道您可以像这样使用单个变量来解构数组:
let one, two, three;
[one, two, three] = arr
但是以两个为增量进行,这可能吗?
最佳答案
另一种方法是通过 ES6 generator function :
let arr = [1, 2, 3, 4, 5, 6, 'a']
function* batch (arr, n=2) {
let index = 0
while (index < arr.length) {
yield arr.slice(index, index + n)
index += n
}
}
let [first, second, third] = batch(arr)
console.log(first)
console.log(second)
console.log(third)
或者更通用的方法,如 @Patrick Roberts 所建议的那样:
let arr = [1, 2, 3, 4, 5, 6, 'a']
function* batch (iterable, length=2) {
let array = [];
for (const value of iterable) {
if (array.push(value) === length) {
yield array;
array = [];
}
}
if (array.length) yield array;
}
let [first, second, third] = batch(arr);
console.log(first)
console.log(second)
console.log(third)
最后是 curried版本:
let arr = [1, 2, 3, 4, 5, 6, 'a']
const batch = length => function* (iterable) {
let array = [];
for (const value of iterable) {
if (array.push(value) === length) {
yield array;
array = [];
}
}
if (array.length) yield array;
}
let [first, second, third] = batch(2)(arr);
console.log(first)
console.log(second)
console.log(third)
关于javascript - 以两个为增量解构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56708541/