我是node.js的初学者,在评估evalMath()函数后我遇到了问题。特别是,将 Math2的值指定为yScale 。
Math2是网页的输入框,引入了一个简单的等式,如“Ir = Vr / R'”。此字符串值从网页传递到node.js上实现的Web服务器。在那里,执行函数evalMath(),它将Vr(带字符串)和R替换为相应的整数值。执行此功能后,获得类似这样的' ANI0 [i] -ANI5 [i] / 10',它存储在变量Math2中。该功能完美无缺。但是,当Math2分配给yScale时,只保存' Ir = Vr / R'而不是执行evalMath()后获得的字符串 - > ' ANI0 [I] -ANI5 [I] / 10&#39 ;.我不确切知道为什么。
if (yScale == 'Math2') {
console.log('Math2 selected');
evalMath(textAD0,textAD1,textAD2,textAD3,textAD4,Math2,Rb,Rc,R,yScale);
yScale = Math2;
console.log ("yScale: "+ yScale);
} else {
console.log("Nothing to change :) - No eqn");
}
function evalMath(labelAD0, labelAD1, labelAD2, labelAD3,
labelAD4, entry, entry1, entry2, entry3, entry4) {
iAD0="",iAD1="",iAD2="",iAD3="",iAD4="",iR="",iRb="", iRc="", iEq="";
var iAD0 = entry.search(labelAD0);
var iAD1 = entry.search(labelAD1);
var iAD2 = entry.search(labelAD2);
var iAD3 = entry.search(labelAD3);
var iAD4 = entry.search(labelAD4);
var iR = entry.search('R');
var iRb = entry.search('Rb');
var iRc = entry.search('Rc');
var iEq = entry.search('=');
if (iAD0 > "0"){ entry = entry.replace(labelAD0,'(ANI0[i]-ANI5[i])'); }
else{console.log("Nothing to change AD0")}
if (iAD1 > "0"){ entry = entry.replace(labelAD1,'(ANI1[i]-ANI5[i])'); }
else{console.log("Nothing to change AD1")}
if (iAD2 > "0"){ entry = entry.replace(labelAD2,'(ANI2[i]-ANI5[i])'); }
else{console.log("Nothing to change AD2")}
if (iAD3 > "0"){ entry = entry.replace(labelAD3,'(ANI3[i]-ANI5[i])'); }
else{console.log("Nothing to change AD3")}
if (iAD4 > "0"){ entry = entry.replace(labelAD4,'(ANI4[i]-ANI5[i])'); }
else{console.log("Nothing to change AD4")}
if (iRb > "0"){ entry = entry.replace('Rb',entry1); }
else{console.log("Nothing to change Rb")}
if (iRc > "0"){ entry = entry.replace('Rc',entry2); }
else{console.log("Nothing to change Rc")}
if (iR > "0"){ entry = entry.replace('R',entry3); }
else{console.log("Nothing to change R")}
if (iEq > "0"){ entry = entry.slice(iEq+1,entry.length); }
else{console.log("Nothing to change iEq")}
console.log("entry: " + entry);
return entry;
}
答案 0 :(得分:0)
将参数传递给函数时,只传递值而不传递变量的引用(对于string,int,float等)。如果您希望能够修改参数的值,请将其传递给对象:
var a = "hello";
var b = "moto";
var obj = {a: "hello", b: "moto"};
function c(p1, p2){ p1 = "yala"; p2="yele";}
c(a, b); // a == hello, b == moto, values not changed
function c2(p1) { p1.a = "yala"; p1.b = "yele";}
c2(obj); // obj.a == "yala", obj.b == "yele"
因此,在您的情况下,请执行以下操作:
var entries = {
Math2: Math2,
Rb: Rb,
Rc: Rc,
R: R
yScale: yScale
};
evalMath(textAD0,textAD1,textAD2,textAD3,textAD4,entries);
entries.yScale = entries.Math2;
console.log ("yScale: "+ entries.yScale);
然后用
替换evalMath的原型 function evalMath(labelAD0, labelAD1, labelAD2, labelAD3,
labelAD4, entries) {
然后在evalMath中,用entry.Math2替换entry1的所有出现,用entry.Rb替换entry2的所有出现,具有entries.Rc的entry3的所有出现,具有entries.R的entry4的所有出现以及具有entry5的所有出现entries.yScale
警告如果影响条目的某些值。它将被修改为函数