JavaScript代码评估包含多个数组的字符串算术表达式

时间:2019-03-01 14:18:55

标签: javascript node.js

我想将算术表达式作为字符串传递给Javascript,并且该字符串可以包含将动态填充的任意数量的数字数组。

例如:我需要评估以下表达式

(pmPdcpVolDlDrb+pmPdcpVolDlSrb)/8/1024 , Where both pmPdcpVolDlDrb and pmPdcpVolDlSrb are numeric arrays

pmPdcpVolDlDrb =[ Array containing values for sensor pmPdcpVolDlDrb read from storage]
pmPdcpVolDlDrb =[ Array containing values for sensor pmPdcpVolDlDrb read from storage]

此表达式可以更改,并且涉及的变量数也可以更改。我需要一种通用的处理方式。我写了下面的代码,它可以达到我的目的。我需要知道是否有更好的标准方法。

// Expression for evaluation where pmPdcpVolDlDrb and pmPdcpVolDlSrb are arrays
expression="(pmPdcpVolDlDrb+pmPdcpVolDlSrb)/8/1024"
// Seperating out the variables from the expression. In my case variable names always start with pm
variables=expression.split(/\W+/).filter(word => word.includes("pm"));
array=[]
for(i=0;i<variables.length;i++){
    array[i]= [1,2,3,4]// Replace with actual code to get the values of arrays to be computed
    if (i===0)
        expression=expression.replace(variables[i],"a")
    else
    expression=expression.replace(variables[i],"array["+i+"][i]")
}
resultantArray=array[0].map((a, i) => eval(expression))

0 个答案:

没有答案