最近遇到个需求说要根据从接口请求到的公式来动态的计算数值。
找寻发现这个Function动态函数创建 ,接下来详细说下这个用法。
Function
动态函数必须用Function对象来定义(Function是js中的一个对象,是固定不变的,规定Function对象的"F"必须大写,当是function的时候,是定义函数的时候所使用的一个关键字:function funName(x,y),当是Function的时候,我们知道是js中的对象)
【const 变量名 = new Function(”参数1“,”参数2“,”参数n“,”执行语句”)】。
我下面写了示例供参考:
/**
*
* @param {*} dataArr 定制项
* @param {*} formula 公式字符串
*/
export function useComputedMain(dataArr, formula) {
//处理公式
let regex = /\[(.+?)\]/g;
let strs = formula.match(regex);
if (!strs) return formula;
const newStrs = strs.map((str) => str.replace(/\[|]/g, ""));
//处理数据
const obj = {};
dataArr.map((item) => {
obj[item.fieldCode] = item.fieldValue;
});
let num = [];
newStrs.map((item) => num.push(obj[item]));
const compute = new Function(newStrs, `return ${formula}`);
let sum = compute(...num);
return sum;
}