2

I'm writing a function to replace all occurrences of variables p and q with their respective values without using eval(), however, I'm running into some unexpected behaviors. BTW, I'm using phpjs for the str_replace

Fiddle: 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(" "));

        }
    }
}

I have this code for replacing all occurrences, but it's not working. I'm alerting the original string entered in every time, however, the string changes. The expected output of the function is p,and,q repeated 4 times, instead, I have p,and,q, then 1,and,1 repeated 3 times. However, I don't seem to have any assignments to str. Does anyone know why this is happening?

1
  • newinput = str assigns ref, use 'newinput = "" + str' to solve the issue Commented Nov 22, 2013 at 19:16

1 Answer 1

3

When you set newinput equal to str, you're still referencing that original object. When you change the value later in newinput you affect the str variable.

If you want to clone the object you can iterate over the properties of str like so:

var newinput = {};
for(var key in str) {
    newinput[key] = str[key];
}

Thus making a clone of your original object and you won't be affecting it's values. Assuming you don't have objects you want to clone inside your str object. If you do, just run this function recursively.

Updated Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.