【问题标题】:Combine and sum the values in multiple arrays合并和求和多个数组中的值
【发布时间】:2014-01-14 16:32:11
【问题描述】:

这里提供了所有相关代码http://jsfiddle.net/DuWGj/,以及 print(appendTo) 语句。

为了简短起见,我制作了 4 个数组。每个数组有 4 个数字。然后我创建一个新数组,其中包含所有这 4 个数组编号,所以它是一个数组。

例如最终结果是

four.myArraysCombined = [5,3,20,12,3,4,18,11,12,5,8,2,1,9,10,6];

但是,当我尝试时

four.myArraysCombined[3] ,它说它是未定义的。

很明显,当我执行以下操作时,它不起作用

var total = 0;
for (var x = 0; x < 16; x++) {
    total += four.myArraysCombined[x]);
}

我希望能够将所有这些数字与 for 循环相加。我已经尝试了几件事,但它一直给我 undefined 或 NaN。

【问题讨论】:

  • 你有没有做过console.log(four.myArraysCombined) 看看你是否真的在生成你认为你拥有的数组?
  • 您可以像这样简单地生成组合数组:myArrays.join().split(",").map(function(entry) { return Number(entry) })
  • 嗯...我不知道是否是错误...但是您将临时数组推入其他空数组...尝试使用=而不是push()我编辑您的小提琴jsfiddle.net/DuWGj/1 - 关注 JS 中的评论

标签: javascript arrays for-loop


【解决方案1】:

发生了什么

运行后:

prePickNumbers(four, 4, 40, 20, 1);

...four.myArraysCombined 的值为:

[[[2, 17, 20, 1], [7, 2, 20, 11], [7, 14, 3, 16], [12, 17, 3, 8]]]

换句话说,这不是您声称的结果。在继续之前,您应该验证您在流程的每个步骤中获得了您认为的结果。就目前而言,您没有扁平数组。你需要先解决这个问题,然后继续迭代和求和。

为什么会这样

最终结构的原因始于prePickNumbers中的以下行:

tempMyArraysCombined.push(objName.myArray[x]);

您每次都将一个 array 推入另一个数组,因此循环后的结果是一个数组数组。但是,然后,您将 那个 结果推送到另一个数组中:

objName.myArraysCombined.push(tempMyArraysCombined);

所以最终结果实际上是一个包含数组数组的数组(请注意上面输出中的额外括号集)。问题是您在流程的每一步都将整个数组推送到输出中,这会造成嵌套混乱。您应该推送每个数组的 元素,而不是数组本身。

如何解决

这是一种可能的解决方案。将prePickNumbers 替换为以下函数:

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]);
        }
    }
}

【讨论】:

  • 这里显示的值是一个包含一项的数组,一项是包含4项的数组。注意三个左方括号。 [[[
【解决方案2】:

你可以试试

 total += four.myArraysCombined[0][x]

【讨论】:

    【解决方案3】:

    我从你的小提琴中提取了这个:

    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);
        tempMyArraysCombined.push(objName.myArray[x]);
        }
        objName.myArraysCombined.push(tempMyArraysCombined); 
    }
    

    将最后一行编辑为:

    function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
        /* your code */
        objName.myArraysCombined=tempMyArraysCombined; //edit this line not push() but =
    }
    

    现在输出 html 中没有“未定义”。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多