在返回作为字符串参数传递的值时使用eval()的正确方法

Correct method of using eval() when returning values passed as string parameters

本文关键字:eval 方法 返回 字符串 参数传递      更新时间:2023-09-26

我将string参数传递给calculate()函数。我需要将它们作为计算值返回。在以下哪种形式中,我正确使用了eval()

数据:

var nums = ['2','3','1'], sum = ['+']; 

第一个版本:

function calculate(a,b,c,d,e)
{
        console.log('Calculating...(plus separators): '+a+' '+b+' '+c+' '+d+' '+e);
        console.log('Calculating...(comma separators): ',a,' ',b,' ',c,' ',d,' ',e);
        console.log('a :',a);
        console.log('b :',b);
        console.log('c :',c);
        console.log('d :',d);
        console.log('e :',e);
    return eval(a+b+c+d+e);
};
console.log('RESULT: ',calculate(nums[0],sum[0], nums[1],sum[0], nums[2]));

第二个版本:

function calculateP(a,c,e)
{
        console.log('Calculating...(plus separators): '+a+' '+c+' '+e);
        console.log('Calculating...(comma separators): ',a,' ',c,' ',e);
        console.log('a: ',a);
        console.log('c: ',c);
        console.log('e: ',e);
    return eval(a+c+e);
};
console.log('precise RESULT: ',calculateP(nums[0], nums[1], nums[2]));

控制台显示"RESULT:6""精确RESULT:231"

哪一个是正确的,如果有的话?在我看来,第一个("RESULT 6")是可以的,但我更愿意确定。

p.S我使用了eval(),因为最初我将以字符串"2+3-(4*3)/7"的形式传递数学表达式,并希望对其进行计算。某种简单的计算器解析器

p.S#2我使用了数组,因为最终我将向该函数传递更多的数组元素。

__________________________________________________________________________

编辑

现在是否正确使用了eval()

function plus(a,b) {
  return a+b;
}
function minus(a,b) {
  return a-b;
}
var expression = 'minus(plus(2, 3),minus(5,3))';
console.log('(2+3)-(5-3) ',eval(expression));
    expression = 'plus(plus(2, 3),minus(5,3))';
console.log('(2+3)+(5-3) ',eval(expression));

我真的相信你几乎可以在任何地方避免eval,但如果你做了不好的事情,那就做好事!

var expression = '2 + 3 - (4 * 3) / 7';
console.log(eval(expression));

数学运算?容易的

function cos(input) {
  return Math.cos(input);
}
function ln(input) {
  return Math.log(input);
}
var expression = '2 + 3 - cos(4 * 3) / ln(7)';
console.log(eval(expression));

你对eval所做的绝对是怪异的,违背了eval的本性。

嗨,你必须像下面这样使用:

var nums = ['2','3','1'], sum = ['+']; 
function calculate(nums)
{
  var res =0;
  for(var i=0;i<nums.length;i++){
    res= res+(parseInt(nums[i]));
  }
    return res;
};
 console.log('RESULT: ',calculate(nums))

只是一个如何在没有eval()的情况下处理字符串和一些值的示例。

var operators = {
        '+': function (a, i) {
            a[i - 1] += a.splice(i, 2)[1];
            return true;
        },
        '*': function (a, i) {
            a[i - 1] *= a.splice(i, 2)[1];
            return true;
        },
        '(': function (a, i) {
            var j = i + 1,
                b;
            while (j < a.length) {
                if (a[j] === ')') {
                    b = a.splice(i + 1, j - i);
                    b.pop();
                    a[i] = calculate(b);
                    return true;
                }
                if (a[j] === '(') {
                    return false;
                }
                j++;
            }
        },
        ')': 0
    },
    precedence = ['(', '*', '+'];
function split(s) {
    var a = s.split(''),
        i = 1;
    while (i < a.length) {
        if (!(a[i - 1] in operators || a[i] in operators)) {
            a[i - 1] += a.splice(i, 1)[0];
            continue;
        }
        i++;
    }
    return a.map(function (b) {
        return b in operators ? b : Number(b);
    });
}
function calculate(a) {
    while (a.length > 1) {
        precedence.some(function (b) {
            return a.some(function (c, i) {
                if (b === c) {
                    return operators[b](a, i);
                }
            });
        });
    }
    return a[0];
}
document.write(calculate(split('12+23*37')) + '<br>'); // 863
document.write(calculate(split('12+23*(2+(3*4)+5)*37')) + '<br>'); // 16181