eval()
函数在 JavaScript
中是一个非常强大的函数
【1】计算简单公式
很多时候如果需要动态的提供计算的公式,需要写一大段的公式计算逻辑去兼容,可能耗费大量的开发成本。为了快速了解 eval
的用法,直接 ① 打开浏览器;② F12 键控制台输入即可验证;
【2】计算混合简单运算
这里的混合简单运算指的是 加减乘除取模运算 增加对应的混合优先级括号()
、中括号[]
进行运算,注意此处常规计算的大括号" { }"
不被计算在内。
【3】调用自定义函数执行
这里是一个很妙,很危险,很谨慎的一种做法,可以算得上是一个弊端了。一起来看看吧(完整演示代码如下):
案例1:直接调用函数字符串执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const b = 80;
// 1 > 2 >= 3 < 4 <=
const fh = {
1: '>',
2: '>=',
3: '<',
4: '<=',
}
const arr = [
{
min: 0,
a1: 1,
b1: 3,
max: 60,
label: 'dengli'
},
{
min: 60,
a1: 2,
b1: 3,
max: 80,
label: 'jige'
},
{
min: 80,
a1: 2,
b1: 4,
max: 100,
label: 'gfl'
}
]
const resultArray = [];
let resultStr = '';
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
const jkeyjson = {
a2: `${b}${fh[item.a1]}${item.min} && ${b}${fh[item.b1]}${item.max}`,
a1: eval(`${b}${fh[item.a1]}${item.min} && ${b}${fh[item.b1]}${item.max}`),
label: item.label
};
let bb = ''
if (fh[item.a1] && !fh[item.b1]) {
bb = `${b}${fh[item.a1]}${item.min}`
} else if (!fh[item.a1] && fh[item.b1]) {
bb = `${b}${fh[item.b1]}${item.max}`
} else {
bb = `${b}${fh[item.a1]}${item.min} && ${b}${fh[item.b1]}${item.max}`
}
item.bb = bb;
item.cc = (eval(bb));
if (eval(bb)) {
resultStr = item.label;
break;
}
resultArray.push(jkeyjson)
}
console.log(resultArray, 'resultArray');
console.log(arr, 'arr');
console.log(resultStr, 'resultStr');
</script>
</body>
</html>