10
var a = 1;
var b = Number(1);
var c = new Number(1);

我想知道这三个陈述之间有什么区别。我知道第一个和第二个语句是一样的,就像if(a===b)给了一样true,但是第三个语句会创建一个number 类型的对象。

我想知道的是这些方法有何不同,其中一种方法会比另一种方法有什么优势?

4

3 回答 3

12

像这样的值1是原语,而不是对象。JavaScript 通常会Number在必要时将数字提升为对象。很少有理由明确地构建一个,当然也没有特别的“优势”。Number(1)尽管Number构造函数是将值强制为数字的几种方法之一,但也没有类似的理由。

于 2012-09-10T15:48:00.363 回答
2

In short, non: the new String() and new Number() constructors are to be ignored if you want to save yourself a world of trouble.
The first two methods you present here assign a numeric constant to the variable, the third way -as you say- creates an object. The value of that object will be 1, but you can change that value without loosing any specific methods you set to the object.

There aren't very many advantages to storing numbers or strings in objects. AFAIK, the only thing you "gain" is a very, very, very slight performance difference over the constants when invoking certain methods, like toExponential etc...
In my view, that isn't worth the trouble of creating objects for all numbers you're bound to use. I think of it as one of the bad parts of JS, meant to make the language look familiar to Java Applet developers.

The second, without the new keyword, allows you to sort-of-type-cast: Number(document.getElementById('formElem').value) === 123; and has its uses (mainly with Date objects, in my experience). But then again, converting to a number can be achieved using the + operator, too: +document.getElementById('formElem').value) === 123

On the whole, just stay well clear of these primitive constructors. The only reason they're still there is because they're objects, and therefore have prototypes. Now THAT is an advantage:

Number.prototype.addOneToString = function()
{
    return (1+this).toString();
};
String.prototype.UpperFirst = function()
{
    return this.charAt(0).toUpperCase() + this.slice(1);
}
var foo = new Number(3);
foo.addOneToString();//returns "4"
foo = new String('foo');
foo.UpperFirst();//Foo

Since JS wraps constant operands in an instance of its object counterpart, when the statement requires it, you can apply prototype methods (either native or self-made ones) to any constant. (Thanks to Pointy for this, and +1)

(3).addOneToString();//"4"
'foo'.UpperFirst();//Foo

So just regard them as legacy quirks, that are still there because of their prototypes.

于 2012-09-10T15:58:32.477 回答
0

在 ES12 及之后,您可以使用以下方式来声明大数。

const oneMillion = 1_000_000;

var oneMillion1 = 1_000_000;

您可以使用分隔符_,以提高可读性

于 2021-06-20T06:54:44.683 回答