Javascript在循环中添加多个数组

标签 javascript html

我正在尝试在 javascript 中添加多个数组。
这是我制作的阵列,并且正在工作。

function getAmountSpent(){

    var amountSpent = ((Math.random() * 500) + 1);
    return amountSpent.toFixed(2)
}

function getGift(){
    var gift = ((Math.random()* 50) + 1);
    return gift.toFixed(2)
}

var names = ["Jeremy","Arun","Alisa","Rohan","Dana"];


var spent = [];
for (let i = 0; i < 5; i++) {
spent.push(getAmountSpent());
}

var gifts = [];
for (let i = 0; i<5; i++) {
gifts.push(getGift());
}

我需要帮助的是在新函数中添加这些数组。我已经开始编写代码,但我不确定出了什么问题。
var totals =[];
for (let i=0; i<5; i++) {
totals.push(getSumTotals())
}

function getSumTotals(a){
    totals= spent+(spent * gifts);
    return totals.toFixed(2)


}

从你所看到的,我试图把总数加起来,就像这样:
totals[0] = spent[0] + (spent[0] * gifts[0]);
totals[1] = spent[1] + (spent[1] * gifts[1]);
totals[2] = spent[2] + (spent[2] * gifts[2]);
totals[3] = spent[3] + (spent[3] * gifts[3]);
totals[4] = spent[4] + (spent[4] * gifts[4]);

如果有帮助,教授添加了函数 getSumTotals(a) 的指导说明,说明:
  This function will return the sum of the elements in array a.
  You will be passing the array that holds your totals to
  the parameter a. Be sure to treat the values in a as numbers.

the table

我不确定这是否有帮助,但这是我文档的输出。
当前总计应等于(花费)+(花费 * 礼物)​​。例如,对于本例中的 Jeremy,当前总数应等于:
36.55 美元 + (36.55 美元*0.0626) = 38.83 美元。由于涉及到许多变量,我不能 100% 确定我应该为函数 getSumTotals(a) 写什么

参数“a”是一个占位符,因为我不确定我需要多少个参数值,以及我需要使用的正确格式。

最佳答案

至于代码...

你俩都是

  • 未将索引传递给 getSumTotals
  • 不在 getSumTotals 中使用此参数来访问您的已花费和礼物数组
  • var totals =[];
    for (let i=0; i<5; i++) {
      totals.push(getSumTotals(i)) // you were missing i
    }
    
    function getSumTotals(idx) { // I took liberties to rename this
      totals = spent[idx] + (spent[idx] * gifts[idx]);
      return totals.toFixed(2);
    }
    

    现在对于数学...

    综上所述,spent[i] + spent[i] * gifts[i] 的数学运算也没有多大意义。这是在问题中指定的吗?

    关于Javascript在循环中添加多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58618620/

    相关文章:

    javascript - 跳过 <img> 的缺失元素

    Javascript - 日期验证 IF 需要语句

    javascript - momentjs 解析德语日期字符串

    html - 使 bootstrap 4 container-fluid 完全流到浏览器窗口的边缘

    javascript - 拖放不适用于溢出自动

    html - html 电子邮件中的背景图像 css - Gmail 不支持

    javascript - 如何使用 Rails + Webpack 配置 Bootstrap 插件?

    javascript - 如何在html5中包含javascript

    html - 在移动设备下方堆叠一个 div

    javascript - 播放和暂停按钮如何使用 javascript 在游戏中工作?