[英]Variable is not changing value
因此,我正在设计一种代码,它将使用户能够创建伪定制操作,可以在特殊的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
我已经对这个问题进行了大约一个小时的故障排除,但我不知道出了什么问题。 非常感谢您的帮助。
在这里,您在给变量赋值之前使用变量oper
:
if(equ.search(oper) !== -1){
oper = t["ops"][i];
未定义的值将转换为空的正则表达式,因此它将始终返回匹配项,这就是第一个运算符起作用的原因。 在下一次迭代中,将为变量分配错误的运算符。
在使用它查找运算符之前,先为其分配运算符:
oper = t["ops"][i];
if(equ.search(oper) !== -1){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.