我正在尝试获取较大组中一个数组的总和。代码更新了第一个数组中的第一个数组值,但是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>
最佳答案
您必须将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>
要访问数组(数组.. of数组)的元素,必须将
[]...[]
彼此相邻放置,而不是像[[...[]]]
这样。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].