문제

I tried to program a function, that converts javascript objects to a http-compatible string. I achieved what I intendet to do, but I don't know why it works. My final function is:

function paramify (p) {
    var n = 0, r = "";
    for (var i in p) {
        r+=(n++==0?"":"&")+i+"="+p[i];
    }
    return r;
}

The version without the ternary operator is:

function paramify (p) {
    var n=0, r="";
    for(var i in p){
        if(n++!=0){
            r+="&"
        }
        r+=i+"="+p[i]
    }
    return r;
}

Example json-object:

{"authToken":"aqsd2","username":"test","password":"1234"}

will become:

authToken=aqsd2&username=test&password=1234

(as intendet)

May somebody explain me, why this works? I didn't expect n++ to become 0 when n is already 0.

도움이 되었습니까?

해결책

It's the difference between pre and post increment. It's explained in this question: ++someVariable Vs. someVariable++ in Javascript

다른 팁

"variable++" is incremented after being evaluated, "++variable" is incremented before being evaluated. Same goes for the "--" operator.

reference at http://msdn.microsoft.com/en-us/library/ie/26k41698(v=vs.94).aspx

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top