javaScript eval 和Function使用

例如:

 

实现任意的计算方式

var arr =  ['+', '-', '*', '/'];

let a = 12 ;// 第一个数

let b = 0.34; // 第二个数

使用eval 方式:

let arr2 = arr.map(item =>{return   a +  item + b}).map(item =>{return eval(  item)})

打印结果

 [12.34, 11.66, 4.08, 35.29411764705882]

 

 

使用  Function  

let arr3 = arr.map(item =>{return   a +  item + b}).map(item =>{return  Function('"use strict";return (' + item + ')')(); })

结果:

 [12.34, 11.66, 4.08, 35.29411764705882]

 

MDN中强烈推荐使用Function  的方式

 

posted @ 2021-11-20 15:10  pointCode  阅读(199)  评论(0)    收藏  举报