0
因此,我设计的代码将使用户能够创建伪特定操作,可以使用特殊的eval()
函数(因为JavaScript是而不是可扩展的语言)。我的问题是,只有第一个变量创建似乎注册和评估。变量不会改变值
我在这里发布一大段代码。
var CMD = function(){
var objs = gAO() /* gets all of the objects */;
// testing for other instances of the CMD object.
this .bool = 0;
for(obj in objs) this .bool ^= !objs[obj]["_aqz39"] // boolean
if(this .bool){
// DEFINING VARS
this .objs = objs;
this["_aqz39"] = true;
this .ops = []; this .eqs = [];
}
}
{ /* init */
var cmd = new CMD();
}
// USER INPUT FOR CREATING 'NEW VARIABLES'
var Operator = function(op,input){
// SYNTAX: "<operator>","x <operator> y = <result, using 'x' and 'y'>"
// EXAMPLE: "#","x # y = 3 * x - y"
this .op = op;
this .eq = input.split("=")[1].trim();
}
// FUNCTION FOR ACTIVATING THE VARIABLE TO BE
// ...RECOGNIZED BY THE CMD's 'EVAL' FUNCTION
activate = function(ind){
cmd.ops.push(ind.op);
cmd.eqs.push(ind.eq);
}
CMD.prototype.eval = function(equ){
// DECLARING VARS
var t = cmd,oper,equation,x,y,i=0;
// LOOPS THROUGH ALL OF THE CHILDREN OF cmd.ops
while (i < t["ops"].length){
// CHECKS TO SEE IF THE INPUT CONTAINS THE SYMBOL
if(equ.search(oper) !== -1){
// the operator
oper = t["ops"][i];
// the equation
equation = t["eqs"][i];
// from the first index to the beginning of the operator
x = equ.slice(0,equ.search(oper)).trim(),
// from right after the operator to the end of the thing
y = equ.slice(equ.search(oper)+1,equ.length).trim();
/* INFORMATION LOGGING */
console.log({x:x,y:y,oper:oper,equation:equation,i:i,t:t,bool: equ.search(oper),len:t["ops"].length})
// RESULT
return eval(eval(equation));
}
// INCREMENTS 'i'
i++;
}
// ELSE
return false;
}
测试#1
var hash = new Operator("#","x # y = 3 * x - y");
var dash = new Operator("q","x q y = y");
activate(dash);
activate(hash);
console.log(cmd.eval("3 q -2")); // RETURNS -2
console.log(cmd.eval("3 # -2")); // RETURNS NOTHING
测试#2
var hash = new Operator("#","x # y = 3 * x - y");
var dash = new Operator("q","x q y = y");
activate(hash); // HASH IS CALLED FIRST THIS TIME
activate(dash);
console.log(cmd.eval("3 q -2")); // RETURNS NaN
console.log(cmd.eval("3 # -2")); // RETURNS 11
我已经解决此事情了大约一个小时,我不知道发生了什么事情错了。帮助是高度赞赏。
这是一个很好的机会,学习如何使用JS调试器! https://developer.chrome.com/devtools/docs/javascript-debugging – zerkms 2014-10-07 22:06:49
我会非常非常谨慎地允许用户输入任何与eval()一样危险的东西。 – 2014-10-07 22:12:00
@zerkms我试着在Chrome和Mozilla中做这件事,除了我已经知道的东西(即'eval()'函数试图评估'#'符号)之外不会产生任何结果。不管怎么说,多谢拉! – 2014-10-07 22:14:14