我必須製作一個具有屬性值的所有組合的數組。如何從屬性值生成變化
屬性/值對象:
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