我试图在更大的组中获得一个数组的总和。代码更新第一个数组中的第一个数组值,但reduce函数不起作用。这是代码:
JavaScript(查看结果的HTML):
var boughtRaw = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]];
var boughtCalc = function (level) {
boughtRaw[0[0]] = 5
var Raw = boughtRaw[level];
window["boughtList" + level] = Raw.reduce(function(a, b) {
return a + b;}, 0);
};
boughtCalc(0);
document.getElementById("debug").innerHTML = boughtList0;
/* Should return 5 */
<span id="debug" style="border: 1px dashed red">Debug</span>
答案 0 :(得分:3)
您必须将boughtRaw[0[0]] = 5
更正为此行boughtRaw[0][0] = 5
。
var boughtRaw = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]];
var boughtCalc = function (level) {
boughtRaw[0][0] = 5; // corrected
var Raw = boughtRaw[level];
window["boughtList" + level] = Raw.reduce(function(a, b) {
return a + b;}, 0);
};
boughtCalc(0);
document.getElementById("debug").innerHTML = boughtList0;
/* return 5 */
<span id="debug" style="border: 1px dashed red">Debug</span>
要访问数组(数组的数组)的元素,您必须将[]...[]
放在彼此旁边,而不是像[[...[]]]
那样。
var element1 = array[0] // get first element of array
var element2 = element1[0] // get first element of element1
.....
var result = elementN[0] // get first element of elementN
可以用
代替var result = array[0][0]...[0].