问题描述
所有相关的code为这里提供,以及打印(appendTo)语句。
All the relevant code is provided here http://jsfiddle.net/DuWGj/ , as well as print(appendTo) statements.
要尽量简短,我正在做4阵列。每个阵列有4个数字。然后,我创建具有它内部的所有那些4阵列数字一个新的数组,所以它是一个阵列。
To keep it short, I'm making 4 arrays. Each array has 4 numbers. Then I create a new array that has all those 4 arrays numbers inside of it, so it's one array.
例如最终的结果是
four.myArraysCombined = [5,3,20,12,3,4,18,11,12,5,8,2,1,9,10,6];
然而,当我尝试
four.myArraysCombined [3]
,它说这是不确定的。
four.myArraysCombined[3]
, it says it's undefined.
所以很明显,当我这样做这是行不通的。
so obviously when I do the following it doesn't work
var total = 0;
for (var x = 0; x < 16; x++) {
total += four.myArraysCombined[x]);
}
我期待能够将所有这些数字与相加的循环。我试过几件事情,但它一直给我不确定或NaN。
I'm looking to be able to add all those numbers together with a for loop. I've tried several things but it keeps giving me undefined or NaN.
推荐答案
运行后:
prePickNumbers(four, 4, 40, 20, 1);
... four.myArraysCombined
的值是:
[[[2, 17, 20, 1], [7, 2, 20, 11], [7, 14, 3, 16], [12, 17, 3, 8]]]
在换句话说,它是不是你要求它是结果。你应该确认你有,你认为你做的在过程中的每一步的,在移动之前的结果。既然这样,你不会有一个扁平的数组。你需要解决这个问题,然后再转移到迭代和总结。
In other words, it is not the result that you claim it is. You should verify that you have the result that you think you do at each step of the process, before moving on. As it stands, you do not have a flattened array. You need to fix that first and then move on to iterating and summing.
究其原因,最终结构开始在下面的行 prePickNumbers
:
The reason for the final structure starts at the following line in prePickNumbers
:
tempMyArraysCombined.push(objName.myArray[x]);
您正在推动一个的阵列的到另一个阵列中的每个时间,所以循环之后的结果是数组的数组。但是,这时,你推的是的结果到另一个数组:
You're pushing an array into another array each time, so the result after the loop is an array of arrays. But, then, you push that result into another array:
objName.myArraysCombined.push(tempMyArraysCombined);
所以,最后的结果实际上是一个包含数组的数组(注意额外的设置输出括号以上)的阵列。问题是,你推整个数组到您的输出在过程中的每一步,这是创建一个嵌套的一塌糊涂。你应该推的元素的每个阵列,而不是数组本身。的
So the final result is actually an array containing an array of arrays (notice the extra set of brackets in the output above). The problem is that you're pushing an entire array into your output at each step in the process, which is creating a nested mess. You should be pushing elements of each array, not the arrays themselves.
下面是一个可能的解决方案。替换 prePickNumbers
具有以下功能:
Here is one possible solution. Replace prePickNumbers
with the following function:
function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
var tempMyArraysCombined = [];
for (var x = 0; x < theNum; x += 1) {
pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
for (var j = 0; j < objName.myArray[x].length; j++) {
objName.myArraysCombined.push(objName.myArray[x][j]);
}
}
}
这篇关于合并和总结在多个阵列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!