var groupArrays = {
"group1" : [
"volvo",
"bmw",
"audi"
],
"group2" : [
"red"
],
"group3" : [
"1991"
]
};
此对象是在过滤汽车列表后创建的,我想创建一些css选择器,用于在javascript中显示已过滤的元素。基本上我想要的是一个带有可能选择器的数组,如下所示:
var selectors = [".volvo.red.1991", ".bmw.red.1991", ".audi.red.1991"];
如果组的数量未知,创建selectors
数组的最简单方法是什么?
答案 0 :(得分:1)
var groupArrays = {
"group1": [
"volvo",
"bmw",
"audi"
],
"group2": [
"red"
],
"group3": [
"1991"
]
};
var selectors = [];
var selector;
for (var g1 = 0; g1 < groupArrays.group1.length; g1++) {
for (var g2 = 0; g2 < groupArrays.group2.length; g2++) {
for (var g3 = 0; g3 < groupArrays.group3.length; g3++) {
selector = "." + groupArrays.group1[g1] +
"." + groupArrays.group2[g2] +
"." + groupArrays.group3[g3];
selectors.push(selector);
}
}
}
console.log(selectors);
更新了任意数量的群组的代码
var groupArrays = {
"group1": [
"volvo",
"bmw",
"audi"
],
"group2": [
"red","green"
],
"group3": [
"1991","1992"
]
};
var selectors = [];
var values = [];
var ga = [];
for (var group in groupArrays) {
ga.push(groupArrays[group]);
}
traverse(ga, 0);
console.log(selectors);
function traverse(ga, index) {
if (index >= ga.length) {
selectors.push("." + values.join("."));
return;
}
var hold = ga[index].slice(0);
var gacopy = ga[index];
while(gacopy.length > 0) {
var pickedValue = gacopy[gacopy.length - 1];
values.push(pickedValue);
gacopy.pop();
traverse(ga, index + 1);
values.splice(values.indexOf(pickedValue), 1);
}
ga[index] = hold;
}
答案 1 :(得分:0)
只需一系列简单的嵌套循环即可。但是,对于以数字开头的 class 1991
,您可能会遇到一些问题。
var selectors = [];
var i = groupArrays.group1.length,
j,
k;
while (i--) {
j = groupArrays.group2.length;
while (j--) {
k = groupArrays.group3.length;
while (k--) {
selectors.push(
'.' + groupArrays.group1[i] +
'.' + groupArrays.group2[j] +
'.' + groupArrays.group3[k]
);
}
}
}
selectors; // [".audi.red.1991", ".bmw.red.1991", ".volvo.red.1991"]
如果groupArrays
中包含未知数量的项目,您可能需要for..in
循环覆盖它并使用生成的密钥递归。
答案 2 :(得分:0)
您可以使用map
功能
var selectors = [];
groupArrays["group1"].map(function(x) {
groupArrays["group2"].map(function(y) {
groupArrays["group3"].map(function(z) {
selectors.push('.' + x + '.' + y + '.' + z)})})});