我在 js 中有以下数组:
var list = [
['nice', 'delicious', 'red'],
['big', 'tiny'],
['apple']
];
我想获得所有可能的变体,例如:
['nice', 'big', 'apple']
['delicious', 'big', 'apple']
['red', 'big', 'apple']
['nice', 'tiny', 'apple']
...
实现此目标的最佳/最 Eloquent 方法是什么?
我试图想出一些非常奇特的东西,比如递归或 maps 和 reduce 的堆栈,但是这个问题似乎没有复杂到足以证明不同于以下内容的东西:
var result = list[0].map(function(item) { return [item]; });
for (var k = 1; k < list.length; k++) {
var next = [];
result.forEach(function(item) {
list[k].forEach(function(word) {
var line = item.slice(0);
line.push(word);
next.push(line);
})
});
result = next;
}
console.log(result);