javascript中的数组组合,错了吗?
Array combinatorics in javascript, It's wrong?
我创建了这个脚本,因为当我收到 n 个数组时需要执行独特的组合。它可以工作,但是当我想存储在最终数组中时,它会写一些不同的东西。
let options = {
"A": ["A1", "A2", "A3", "A4"],
"B": ["B1", "B2"],
"C": ["C1", "C2", "C3", "C4", "C5"],
};
let keys = Object.getOwnPropertyNames(options);
let size = keys.length;
let final = [];
function combinate(n, o) {
for (let i = 0; i < options[keys[n]].length; i++) {
if (n === (size - 1)) {
o = {};
}
o[keys[n]] = options[keys[n]][i];
if ((n - 1) >= 0) {
combinate(n - 1, o);
}
if (n === 0) {
console.log(o);
final.push(o);
}
}
}
if (size > 0) combinate(size - 1, {});
console.log("-----------------------------------")
console.log(final);
您在数组中多次保存对同一对象的引用,并对该对象进行了更改。您需要将对象的新副本放入数组中。
更改:final.push(o);
到 final.push(Object.assign({}, o));
或者,更直接地说:final.push({A:o.A, B:o.B, C:o.C});
需要将对象的引用传入函数,然后将修改后的对象复制到final数组
let options = {
"A": ["A1", "A2", "A3", "A4"],
"B": ["B1", "B2"],
"C": ["C1", "C2", "C3", "C4", "C5"], };
let keys = Object.getOwnPropertyNames(options);
let size = keys.length;
let final = [];
function combinate(n, o, fooFinal) {
for (let i = 0; i < options[keys[n]].length; i++) {
if (n === (size - 1)) {
o = {};
}
o[keys[n]] = options[keys[n]][i];
if ((n - 1) >= 0) {
combinate(n - 1, o, fooFinal);
}
if (n === 0) {
console.log(o);
fooFinal.push(o);
}
}
if(n===size-1){
return fooFinal;
}
}
if (size > 0){
final = combinate(size - 1, {},[]);
}
console.log("-----------------------------------")
console.log(final);
我创建了这个脚本,因为当我收到 n 个数组时需要执行独特的组合。它可以工作,但是当我想存储在最终数组中时,它会写一些不同的东西。
let options = {
"A": ["A1", "A2", "A3", "A4"],
"B": ["B1", "B2"],
"C": ["C1", "C2", "C3", "C4", "C5"],
};
let keys = Object.getOwnPropertyNames(options);
let size = keys.length;
let final = [];
function combinate(n, o) {
for (let i = 0; i < options[keys[n]].length; i++) {
if (n === (size - 1)) {
o = {};
}
o[keys[n]] = options[keys[n]][i];
if ((n - 1) >= 0) {
combinate(n - 1, o);
}
if (n === 0) {
console.log(o);
final.push(o);
}
}
}
if (size > 0) combinate(size - 1, {});
console.log("-----------------------------------")
console.log(final);
您在数组中多次保存对同一对象的引用,并对该对象进行了更改。您需要将对象的新副本放入数组中。
更改:final.push(o);
到 final.push(Object.assign({}, o));
或者,更直接地说:final.push({A:o.A, B:o.B, C:o.C});
需要将对象的引用传入函数,然后将修改后的对象复制到final数组
let options = {
"A": ["A1", "A2", "A3", "A4"],
"B": ["B1", "B2"],
"C": ["C1", "C2", "C3", "C4", "C5"], };
let keys = Object.getOwnPropertyNames(options);
let size = keys.length;
let final = [];
function combinate(n, o, fooFinal) {
for (let i = 0; i < options[keys[n]].length; i++) {
if (n === (size - 1)) {
o = {};
}
o[keys[n]] = options[keys[n]][i];
if ((n - 1) >= 0) {
combinate(n - 1, o, fooFinal);
}
if (n === 0) {
console.log(o);
fooFinal.push(o);
}
}
if(n===size-1){
return fooFinal;
}
}
if (size > 0){
final = combinate(size - 1, {},[]);
}
console.log("-----------------------------------")
console.log(final);