我有以下数组:
var Set = ("BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a").split(',');
按顺序工作,我想一次取三个元素并将每个元素分配给一个变量。我想要的结果是:
var Aggreg = ["BENELUX", "Western Europe"]
var Country = ["Luxembourg", "France"]
var Product = ["PP3a", "PP6a"]
'Set'中元素的顺序始终是顺序的,并且总是3的倍数。我确信这是一种聪明有效的方法。有人能指出我正确的方向吗?
答案 0 :(得分:2)
您可以使用解构赋值,增量变量来反映索引
var set = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(",");
var n = 0, m = 3;
var fn = (arr, a = 0, b = 3) => [arr[a], arr[b]];
var [Aggreg, Country, Product] = [
fn(set),
fn(set, ++n, ++m),
fn(set, ++n, ++m)
];
console.log(Aggreg, Country, Product);

替代地
var set = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(",");
var fn = function* (arr) {
var n = 0, m = 3;
while (m < arr.length) {
yield [arr[n], arr[m]];
n += 1; m += 1;
}
};
var [Aggreg, Country, Product] = fn(set);
console.log(Aggreg, Country, Product);
&#13;
答案 1 :(得分:1)
只需使用模数过滤您的数组(如果您确定数据 - 在这种情况下,请确保获得3个数组大小的倍数):
const data = "BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a".split(",")
function extract(data, shift) {
return data.filter((value, index) => (index % 3) === shift)
}
const Aggreg = extract(data, 0)
const Country = extract(data, 1)
const Product = extract(data, 2)
console.log(Aggreg, Country, Product)
&#13;
答案 2 :(得分:1)
您可以使用.reduce()
将每个部分放入单个对象内的数组中,然后使用解构赋值来分配单个变量,如下所示:
var Set = ("BENELUX,Luxembourg,PP3a,Western_Europe,France,PP6a").split(',');
var {Aggreg, Country, Product} = Set.reduce(function (result, curr, index) {
if (index % 3 === 0) {
result.Aggreg.push(curr);
}
else if (index % 3 === 1) {
result.Country.push(curr);
}
else {
result.Product.push(curr);
}
return result;
}, {Aggreg: [], Country: [], Product: []})
console.log(Aggreg);
console.log(Country);
console.log(Product);
&#13;
答案 3 :(得分:1)
可以使用简单的for(reset($broken);$kv = myEach($broken);) {...}
:
Array.prototype.forEach()