我正在寫一個函數,用它們各自的值替換所有出現的變量p
和q
,但不使用eval()
,但是,我遇到了一些意外的行爲。順便說一句,我使用phpjs的str_replace函數Javascript意外的分配行爲
小提琴:http://jsfiddle.net/5Uedt/2/
function table(str){
str=str_replace(["nand","nor","implies","equals","not","xor","and","or","(",")"],[" 3 "," 4 "," 5 "," 6 "," 7 "," 8 ", " 9 ", " 10 ", " (",") "],str).replace(/\s{2,}/g, ' ').trim();
str=str_replace(["3","4","5","6","7","8", "9", "10", "(",")"],["nand","nor","implies","equals","not","xor","and","or","(",")"],str).split(" ");
var vars={p:1,q:1};
for(vars['p']=1;vars['p']>=0;vars['p']--){
for(vars['q']=1;vars['q']>=0;vars['q']--){
alert(str);
newinput=str;
for(var i=0;i<newinput.length;i++){
var token=newinput[i];
if(token.length===1){
console.log(newinput[i]);
newinput[i]=vars[newinput[i]];
}
}
// console.log(n.join(" "));
}
}
}
我對更換所有出現這樣的代碼,但它不工作。我警告每次輸入的原始字符串,但是,字符串會發生變化。函數的預期輸出是重複4次,取而代之,我有,然後1,and,1
重複3次。但是,我似乎沒有任何str的任務。有誰知道爲什麼會發生這種情況?
newinput = STR分配ref時,使用 'newinput = 「」 + STR' 解決問題 –