最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I always use ++ or -- as a shorthand for parseFloat? - Stack Overflow

programmeradmin3浏览0评论

!! 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?

!! 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?

Share Improve this question asked Oct 11, 2011 at 1:24 MohsenMohsen 65.9k36 gold badges163 silver badges187 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

Just use a single + (unary plus operator). It is a mon 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.

发布评论

评论列表(0)

  1. 暂无评论