It's the difference between pre and post increment. It's explained in this question: ++someVariable Vs. someVariable++ in Javascript
strange behavior with ternary operator
-
01-07-2022 - |
質問
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.
解決
他のヒント
"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
所属していません StackOverflow