首页 > 解决方案 > 是否可以“计算”一个数组名称(例如通过连接两个字符串?),以便访问现有数组?

问题描述

仍然处于学习的早期阶段。但试图以比要求的更复杂的方式完成代码练习 - 并且无法解决这个问题。目标是构建一个接收数组作为参数的函数,然后函数上的循环将对嵌入的值进行一些数学运算。

我假设用户应该能够选择要计算的数组,并且我尝试使用浏览器提示来接收该请求(例如 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

标签: javascriptarraysfunctionobjecttypes

解决方案


推荐阅读