What is the difference between “new Number(…)” and “Number(…)” in JavaScript?

后端 未结 4 721
青春惊慌失措
青春惊慌失措 2020-12-02 01:48

In Javascript, one of the reliable ways to convert a string to a number is the Number constructor:

var x = Number(\'09\'); // 9, because it defa         


        
4条回答
  •  囚心锁ツ
    2020-12-02 02:37

    Number returns a primitive number value. Yeah, it's a bit odd that you can use a constructor function as a plain function too, but that's just how JavaScript is defined. Most of the language built-in types have weird and inconsistent extra features like this thrown in.

    new Number constructs an explicit boxed Number object. The difference:

    typeof Number(1)      // number
    typeof new Number(1)  // object
    

    In contrast to Java's boxed primitive classes, in JavaScript explicit Number objects are of absolutely no use.

    I wouldn't bother with either use of Number. If you want to be explicit, use parseFloat('09'); if you want to be terse, use +'09'; if you want to allow only integers, use parseInt('09', 10).

提交回复
热议问题