我必须制作一个具有属性值的所有组合的数组。如何从属性值生成变化
属性/值对象:
let attributes = {
color: ['red', 'green', 'blue'],
sizes: ['sm', 'md', 'lg'],
material: ['cotton', 'wool']
}
我需要使所有可能的组合作为这样的阵列。
color sizes material
red sm cotton
red sm wool
red md cotton
red md wool
red lg cotton
red lg wool
blue sm cotton
blue sm wool
blue md cotton
blue md wool
blue lg cotton
blue lg wool
green sm cotton
green sm wool
green md cotton
green md wool
green lg cotton
green lg wool
属性类型和值计数都是不确定的(至少为1)。我怎样才能做到这一点?
这是我迄今为止
// keys = ['color', 'sizes', 'material']
// attributes is the same as above.
for (let keysIndex = 0; keysIndex < keys.length; keysIndex++) {
let key = keys[i];
let values = attributes[key];
//loop through each value
for (let valuesIndex = 0; valuesIndex < values.length; valuesIndex++) {
// for each value, loop through all keys
for (let keysIndex2 = 0; keysIndex2 < keys.length; keysIndex2++) {
if (keysIndex === keysIndex2) {
continue;
}
for (let valuesIndex2 = 0; valuesIndex2 < values.length; valuesIndex2++) {
// What do I do from here?
// Not sure if this is even the right path?
}
}
}
}
您感兴趣的任何特定语言? – smarx
Javascript会很好,但我只是在寻找算法。 – Jeff
它被称为*笛卡尔产品*(并且有很多JS解决方案,例如[this one])(http://stackoverflow.com/a/15310051/1048572)) – Bergi