日期:2014-05-16  浏览次数:20543 次

在线等一分析思路
下面为一个计算表达式,其中a,b,c,d分别代码+   -   *   /  
求它的分析思路onclick= "aa( 'b(a(c(2,3),1,2),c(a(c(3,7),1,2),4)) '

------解决方案--------------------
<script>
function a(){//参数可以任意个
var len=arguments.length;
var returnValue=0;
for(var i=0;i <len;i++){
returnValue+=arguments[i];
}
return returnValue;
}
function b(i,j){
return i-j;
}
function c(i,j){
return i*j;
}
function d(i,j){
return i/j;
}
var value=b(a(c(2,3),1,2),c(a(c(3,7),1,2),4));
alert(value);
</script>
------解决方案--------------------
eval
------解决方案--------------------
<html>
<head>
<meta http-equiv= "content-type " content= "text/html; charset=gb2312 "/>
<link rel= "stylesheet " href= ".css "/>
<title> New Document </title>
<style type= "text/css ">
<!--

-->
</style>
<script type= "text/javascript ">
<!--

var exp = "b(a(c(2,3),1,2),c(a(c(3,d(28,4)),1,2),4)) ";

function Node(opcode,pNode){
this.opcode = opcode;
this.pNode = pNode;
this.childNodes = [];
}
var rn = new Node( "a ",null);
var stack = [];
stack.push(rn);
function parseExp(s){
s = s.replace(/\s/g, " ");
while(s.length > 0){
if(/^(a|b|c|d)/.test(s)){
var pn = stack.getLast();
var n = new Node(s.charAt(0),stack.getLast());
if(pn) pn.childNodes.push(n);
s = s.substring(RegExp.lastIndex);
}
else if(/^\(/.test(s)){
stack.push(n);
s = s.substring(1);
}
else if(/^\)/.test(s)){
stack.pop();
s = s.substring(1);
}
else if(/^\d+/.test(s)){
var pn = stack.getLast();
var n = new Node(RegExp.lastMatch,pn);
pn.childNodes.push(n);
s = s.substring(RegExp.lastIndex);
}
else{
s = s.substring(1);
}
}
}
function cal(n){
var code = n.opcode;
var rslt = 0;
if(/^\d+$/.test(code)) return parseInt(code,10);
else{
switch(code){
case "a ":
for(var i=0,l=n.childNodes.length;i <l;i++)
rslt += cal(n.childNodes[i]);
break;
case "b ":
rslt = cal(n.childNodes[0]);
for(var i=1,l=n.childNodes.length;i <l;i++)
rslt -= cal(n.childNodes[i]);
break;
case "c ":
rslt = 1;
for(var i=0,l=n.childNodes.length;i <l;i++)
rslt *= cal(n.childNodes[i]);
break;
case "d ":
rslt = cal(n.childNodes[0]);
for(var i=1,l=n.childNodes.length;i <l;i++)
rslt /= cal(n.childNodes[i]);
break;
default: alert( "错啦!code: " + code); break;
}
}
/*
var str = "opcode : " + n.opcode + "\n ";
for(var i=0;i <n.childNodes.length;i++)