我有一个对象。我想循环遍历其中一个属性:本身是一个包含值的数组。对于这些值中的每一个,我想输出一个包含每个子数组的代表值的数组,以便输出每个可能的值组合。如果子数组中有多个值,则应允许一次最多1个值。在这一点上,我认为它应该“跳到”下一个(并为所有其他人做同样的事情),但我不确定如何。结果应如下所示:
RABBIT: GREY, FURRY, BOUNCES, CUTE
RABBIT: WHITE, FURRY, BOUNCES, CUTE
RABBIT: RED, FURRY, BOUNCES, CUTE
RABBIT: GREY, FURRY, SCAMPERS, CUTE
RABBIT: WHITE, FURRY, SCAMPERS, CUTE
RABBIT: RED, FURRY, SCAMPERS, CUTE
数组(以及它的子数组)将具有未知长度,因此我使用了for循环。这是迄今为止的代码:
window.onload = function (){
var myObject = {
name: 'RABBIT',
arrayOfValues : [
['GREY','WHITE','RED'],
['FURRY'],
['BOUNCES', 'SCAMPERS'],
['CUTE']
]
};
var results = [];
for (i=0;i<myObject.arrayOfValues.length;i++){
for (j=0; j<myObject.arrayOfValues[i].length;j++){
if(myObject.arrayOfValues[i].length>1) {
var currentProperty = myObject.arrayOfValues[i][j];
myFunc();
}
else {
var currentProperty = myObject.arrayOfValues[i][0];
myFunc();
};
};
};
function myFunc(){
results = results.concat(currentProperty);
if (results.length == myObject.arrayOfValues.length){
var finalResults = myObject.name + ': ' + results
console.log(finalResults);
};
};
};
PS - 数据的形式并非一成不变,我只是为了方便使用了一个对象。
谢谢,保罗
答案 0 :(得分:3)
您可以使用递增的索引参数进行递归函数调用,也可以使用附加字符串新部分并返回的字符串进行。
var arrayOfArrays = [
['big', 'red'],
['red', 'yellow', 'blue'],
['dog', 'cat']
];
var strings = [];
function eachStep(string_so_far, array_index) {
if (array_index < arrayOfArrays.length) {
for (var i = 0; i < arrayOfArrays[array_index].length; i++) {
var string_for_this_step = string_so_far + arrayOfArrays[array_index][i] + " ";
var string_returned = eachStep(string_for_this_step, array_index+1);
if (string_returned !== "") {
strings.push(string_returned);
}
}
return "";
} else {
return string_so_far;
}
}
eachStep("", 0);
console.log(strings);
答案 1 :(得分:2)
递归是这里的原生解决方案:
// Object as described by question:
var myObject = {
name: 'RABBIT',
arrayOfValues: [
['GREY', 'WHITE', 'RED'],
['FURRY'],
['BOUNCES', 'SCAMPERS'],
['CUTE']
]
};
function permutations(arrays, current_array, idx, results) {
// Init head and results in case this is the first iteration:
idx = idx || 0;
results = results || [];
current_array = current_array || [];
// If there's nothing more to add:
if (arrays.length == idx) {
results.push(current_array);
return;
}
// Otherwise, iterate current level and concat values, while calling next level:
arrays[idx].forEach(function(subArrayItem) {
permutations(arrays, current_array.concat(subArrayItem), idx + 1, results)
});
return results;
}
上面的函数将返回一组包含所有组合的数组,接下来是一个用于打印的辅助函数:
// Helper method to print resulting arrays:
function print(obj) {
var separator = "\n"
var prefix = obj.name + ": ";
// Joins the resulting sets with the prefix, and returns printable string:
return prefix + permutations(obj.arrayOfValues).join(separator + prefix)
}
console.log(print(myObject));