math - Can't subtract two JavaScript numbers -



math - Can't subtract two JavaScript numbers -

both pos1 , pos2 javascript numbers, yet when subtract 1 other, nan.

http://jsfiddle.net/2akel/2/

var str = "2014/6/3 "; var y = str.substr(2,2); var pos1 = str.indexof("/"); var pos2 = str.indexof("/", pos1+1); pos2 = ((pos2-pos1)==2 ? 1 : 2 ); var m = str.substr(pos1+1, pos2); var d = str.substr(pos2+1); var = (m.length < 2 ? str("0") + m : m) + "/" + (d.length = 2 || "0" + d) + "/" + y + "*"; alert(pos1 + "|" + pos2 + "|" + m + "|" + pos2);

the problem lies in javascript rules order of evaluation. alert look evaluated if written this:

alert((((((((pos1 + "|") + pos2) + "|") + m) + "|") + pos2) - pos1));

thus "pos2" appended string before "pos1" subtracted. unlike add-on operator, there no string semantics -, string ends nan.

write line this:

alert(pos1 + "|" + pos2 + "|" + m + "|" + (pos2-pos1));

by parenthesizing subtraction operation, forcefulness result computed before rest of string constructed.

also, code @ 1 point included phone call non-existant function "str", , causing error.

javascript math casting int nan

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -