How to convert string equation to number in javascript?

前端 未结 5 998
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 03:04

How to convert string equation to number in javascript?

Say I have \"100*100\" or \"100x100\" how do I evaluate that and convert to a number?

5条回答
  •  太阳男子
    2020-12-20 04:02

    I have a different take on the users answers here that gives an output using split but also recreates the original equation. The other answers I saw used split but didn't really give a correlation that could be parameterized of the original equation in starting out as string format.

    Using split() and for is NOT a good solution but I use it here to illustrate the better solution that doesn't require knowing the number of numbers in the array (which would be reduce). The reason why this works is that in effect it acts like reduce but it requires you to edit the for loop multiplier based on how large the array is:

    let someEnvironmentVariable = '3*3*3'
    let equationString = someEnvironmentVariable;
    // regex to match anything in the set i.e. * and + << not sure if need the ending +
    let re = /[\*\+]+/;
    let equationToNumberArray = equationString.split(re).map(Number);
    let equationResolver = 0;
    for (const numericItem of equationToNumberArray) {
      // recreate the equation above
      equationResolver += numericItem*numericItem;
    }
    
    console.log(equationResolver);
    

    A more elegant solution would be to use: split(), map() and reduce()

    let someEnvironmentVariable = '3*3*4*3'
    let equationString = someEnvironmentVariable;
    // regex to match anything in the set i.e. * and + << not sure if need the ending +
    let re = /[\*\+]+/;
    let equationToNumberArray = equationString.split(re).map(Number);
    
    let arrayMultiplier = equationToNumberArray.reduce((a, b) => a * b);
    
    console.log(arrayMultiplier);
    

    Using reduce allows you to iterate through the array and perform a calculation on each item while maintaining the previous calculation on the previous item.

    Note: what I don't like about either solution is that even reduce requires only one mathematical operation for an array set. A better solution would be code something that detects the operators and includes that in the overall solution This allows you to not use the dreaded eval() but also keep the original equation intact for later processing.

提交回复
热议问题