[['red','yellow'],['xl','xxl']]
上面是一系列衣服的变种,如何在下面打印4组:
red xl, red xxl, yellow xl and yellow xxl
这似乎很容易,但因为它可能是更多数据,如另一个数组(或更多),在这种情况下,我无法执行数据[0]或数据[1]。
答案 0 :(得分:0)
这应该有效:
// data to process and print
var data = [['red','yellow'],['xl','xxl'], ['boy', 'girl']];
var combinations = [], // will hold the running processed strings as we iterate
temp = [], // temporary array
isFirstPropSet = true; // flag to determine if we are processing the first property set (colors in this case)
// for each property set
data.forEach(function(datum) {
// if it isn't the first property set, make a copy into temp and reset our combinations array
if (!isFirstPropSet) {
temp = combinations.splice(0);
combinations = [];
}
// for each property in the current property set
datum.forEach(function(prop) {
// if it is the first property set, simply add it to the current running list
if (isFirstPropSet) {
combinations.push(prop);
} else {
// otherwise for each of the previous items, lets append the new property
temp.forEach(function(comb) {
combinations.push(comb + ' ' + prop);
});
}
});
// make sure to unset our flag after processing the first property set
isFirstPropSet = false;
});
// print out all the combinations
combinations.forEach(function(comb) {
console.log(comb);
});
console.log('-----------------');