计算字符, 把拥有公式的字符计算结果出来

直接上脚本,如下:

              
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
/** msg: 计算字符 param:<string> return:<number> 例子: getCode('?+1=2') // 1 getCode('2*?=6') // 3 getCode('8/4=?') // 2 */ var getCode = function(str){ try{ var one, two, three, fuhao, result; // 去除空格 str = str.replace(/\s/g, ''); if(str.indexOf('=') == '-1'){ return false; } if(str.indexOf('?') == '-1'){ return false; } // 将运算号取出来 fuhao = str.indexOf('+') != '-1' ? '+' : ( str.indexOf('-') != '-1'? '-' : ( str.indexOf('*') != '-1' ? '*' : (str.indexOf('/') != '-1' ? '/' : false ) ) ) if(fuhao === false){ return fuhao; } one = str.split(fuhao)[0]; two = str.split(fuhao)[1].split('=')[0]; three = str.split('=')[1]; if(one === '?'){ fuhao = fuhao == '+' ? '-' : ( fuhao == '-' ? '+' : ( fuhao == '*' ? '/' : '*') ); result = eval('('+ Number(three) + fuhao + Number(two) +')'); }else if(two === '?'){ if(fuhao == '-' || fuhao == '/'){ three = Number(one) + Number(three); one = Number(three) - Number(one); three = Number(three) - Number(one); } fuhao = fuhao == '+' || fuhao == '-' ? '-' : '/'; result = eval('('+ Number(three) + fuhao + Number(one) +')'); }else if(three === '?'){ result = eval('('+ Number(one) + fuhao + Number(two) +')'); } return result != 'Infinity' ? result: false; }catch(e){ return false; } return false; }

有用记得点个赞 😃

本文于 2018/3/23 上午 发布在 编程 分类下,当前已被围观 2021 次

相关标签:js

永久地址:https://blog.pandashuai.com/article/8