!!
always works fine for converting String, undefined
, Object and Number types to Boolean type in JavaScript:
!!0 // false
!!1 // true
!!10 // true
!!"" // true
!!"any" // true
!!undefined // false
!!null // false
!!NaN // false
!!{} // true
It seems using !!
is totally safe. I've seen people using this for converting variables.
But I'm not sure about ++
or --
for converting String types to Number types. In these examples it looks using ++
for converting is safe:
var ten = "10";
ten++ // 10
var nineHalf = "9.5";
nineHalf++ // 9.5
var n = "-10.06";
n++ // -10.06
Is there any case that ++
/--
don't work as parseFloat
?
Just use a single +
(unary plus operator). It is a common practice just like !!
for booleans.
(+"10.06")
The ++
version makes me afraid of the increment operators doing evil tricks when I'm not looking.
Edit: And of course, the postIncrement operator doesn't even work on string literals.
"10.06"++ //syntax error
The only thing is that it has the side effect of adding one to the original variable. The effect of
var n = "-10.06";
n++
for example, is the same as
var n = "-10.06";
Number(n)++
Basically, any math operator when applied to a string will first convert it to a number using the Number
function.
精彩评论