因此,我设计了一个代码,使用户能够创建一个可以在特殊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
我已经解决了这个问题大约一个小时,我不知道出了什么问题。帮助 高度 赞赏。
答案 0 :(得分:1)
在您为其分配任何内容之前,您正在使用变量oper
:
if(equ.search(oper) !== -1){
oper = t["ops"][i];
未定义的值将转换为空的正则表达式,因此它将始终返回匹配,这就是第一个运算符工作的原因。在下一次迭代中,变量将被赋予错误的运算符。
在使用操作符查找操作符之前为其分配操作符:
oper = t["ops"][i];
if(equ.search(oper) !== -1){