javascript - 是否可以“计算”一个数组名称(例如通过连接两个字符串?),以便访问现有数组?
问题描述
仍然处于学习的早期阶段。但试图以比要求的更复杂的方式完成代码练习 - 并且无法解决这个问题。目标是构建一个接收数组作为参数的函数,然后函数上的循环将对嵌入的值进行一些数学运算。
我假设用户应该能够选择要计算的数组,并且我尝试使用浏览器提示来接收该请求(例如 Bills)。
//WHAT I WANTED TO AVOID
//user enters value in prompt, this is passed to the function as a string
function processUserInput(promptResponse){
if(promptResponse == 'Bills'){
calcAverage(arrayBills);
} else if (promptResponse == 'Tips'){
calcAverage(arrayTips);
} else {
calcAverage(arrayTotals);
}
return calcAverage;
}
//WHAT I WAS ATTEMPTING TO DO
//user enters value in prompt, this is passed to the function as a string
//and the goal is to access the array named "arrayBills"
function calcAverage(promptResponse){
let runningTotal = 0;
promptResponse = 'array' + promptResponse;
for (let i = 0; i <= ['promptResponse'].length - 1; i++) {
runningTotal = ['promptResponse'][i] + runningTotal;
}
return runningTotal / ['promptResponse'].length;
}
这可能吗?我无法让它工作,也无法在网上找到很多有意义的东西。我的假设是可以计算给定的对象,并且数组是对象,因此......
无论如何 - 在此先感谢您提供任何建议或指向更好资源的建议。
干杯J
解决方案
推荐阅读
- rust - 如何解除阻塞未来的线程并返回结果
- python - 如果条件,在python中分配错误的值
- java - 分组结果的方面计数
- c++ - win32 计时器是否归其调用线程所有?
- .net-core - 将 WSDL 添加到 .NET Core 项目
- javascript - 如何解决 ReferenceError: google 没有使用脚本在 Angular 中定义?
- php - 以相反的顺序显示最新的分类帖子
- mongodb - 使用sails js在mongo db中上传图像的简单方法
- redis - Vertx 3.7.0+ 使用 RedisAPI - HMSET
- r - 为 Dataframe 执行 R 代码时的因素错误