gpt4 book ai didi

JavaScript:减少麻烦

转载 作者:行者123 更新时间:2023-11-29 19:26:11 28 4
gpt4 key购买 nike

我正在尝试获取较大组中一个数组的总和。代码更新第一个数组中的第一个数组值,但 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>


要访问数组(数组的...数组的)元素,您必须[]...[]彼此相邻放置,而不是像这样[[...[]]]

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].

关于JavaScript:减少麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685332/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com