我正在编写一个函数来替换所有出现的变量p
和q
及其各自的值,而不使用eval()
,但是,我遇到了一些意想不到的行为。顺便说一句,我正在使用phpjs作为str_replace
小提琴: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(" "));
}
}
}
我有这个代码来替换所有的事件,但它不起作用。我警告每次输入的原始字符串,但字符串会发生变化。该函数的预期输出为p,and,q
重复4次,相反,我有p,and,q
,然后1,and,1
重复3次。但是,我似乎没有对str的任何任务。有谁知道为什么会这样?
答案 0 :(得分:3)
当您将newinput
设置为str
时,您仍然会引用该原始对象。当您稍后在newinput
中更改该值时,会影响str
变量。
如果要克隆对象,可以迭代str
的属性,如下所示:
var newinput = {};
for(var key in str) {
newinput[key] = str[key];
}
因此,复制原始对象并且不会影响它的值。假设您没有要在str
对象内克隆的对象。如果这样做,只需递归运行此函数。