'arr'数组是根据用户输入动态创建的,因此其内容会在功能版本中发生变化。用户输入可以是任何长度,因此可能不一定包含5个单词。问题是我不确定如何使用不同数量的子项动态创建words
对象,以便将其推送到combos
的正确成员。
var arr = [
[
["this", 0],
["is", 1],
["a", 2],
["complete", 3],
["sentence", 4],
["with", 5],
["index", 6],
["data", 7]
]
];
var partOne = {
two: [],
three: [],
four: [],
five: []
}
var len = arr.length;
var print = [];
for (var i = 0; i < len; i++) {
var lenGr = arr[i].length;
for (var j = 0; j < lenGr - 1; j++) {
partOne.two.push({
"words": {
"word1": arr[i][j],
"word2": arr[i][j + 1]
}
});
}
for (j = 0; j < lenGr - 2; j++) {
partOne.three.push({
"words": {
"word1": arr[i][j],
"word2": arr[i][j + 1],
"word3": arr[i][j + 2]
}
});
}
for (j = 0; j < lenGr - 3; j++) {
partOne.four.push({
"words": {
"word1": arr[i][j],
"word2": arr[i][j + 1],
"word3": arr[i][j + 2],
"word4": arr[i][j + 3]
}
});
}
for (j = 0; j < lenGr - 4; j++) {
partOne.five.push({
"words": {
"word1": arr[i][j],
"word2": arr[i][j + 1],
"word3": arr[i][j + 2],
"word4": arr[i][j + 3],
"word5": arr[i][j + 4]
}
});
}
}
console.log("Current solution : ");
console.log(partOne);
var partTwo = {
two: [],
three: [],
four: [],
five: []
};
for (i = 0; i < len; i++) {
var lenGr = arr[i].length;
$.each(partTwo, function(ind, val) {
for (var j = 1; j < 4; j++) {
for (var k = 0; k < lenGr - j; k++) {
// Populate 'partTwo' dynamically, in the same format as partOne.
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 0 :(得分:0)
我只提供了一个监视j
的switch语句,以确定在该迭代期间计算的数组成员数,然后重复原始代码以将新对象推送到partTwo
。可能有一个更优雅的解决方案。
var arr = [
[
["this", 0],
["is", 1],
["a", 2],
["complete", 3],
["sentence", 4],
["with", 5],
["index", 6],
["data", 7]
]
];
var partTwo = {
two: [],
three: [],
four: [],
five: []
};
var len = arr.length;
for (i = 0; i < len; i++) {
var lenGr = arr[i].length;
for (var j = 1; j < 5; j++) {
for (var k = 0; k < lenGr - j; k++) {
switch (j) {
case 1:
partTwo.two.push({
"words": {
"word1": arr[i][k],
"word2": arr[i][k + 1]
}
});
break;
case 2:
partTwo.three.push({
"words": {
"word1": arr[i][k],
"word2": arr[i][k + 1],
"word3": arr[i][k + 2]
}
});
break;
case 3:
partTwo.four.push({
"words": {
"word1": arr[i][k],
"word2": arr[i][k + 1],
"word3": arr[i][k + 2],
"word4": arr[i][k + 3]
}
});
break;
case 4:
partTwo.five.push({
"words": {
"word1": arr[i][k],
"word2": arr[i][k + 1],
"word3": arr[i][k + 2],
"word4": arr[i][k + 3],
"word5": arr[i][k + 4]
}
});
break;
default:
console.log("Error with j switch.");
}
}
}
}
console.log(partTwo);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;