问题描述
var a = 1;
var b = Number(1);
var c = new Number(1);
我想知道这三个陈述之间有什么区别。
我理解第一和第二个陈述是相同的,因为如果(a === b)
给出 true
,但第三个将创建一个类型为number的对象。
I was wondering what is the difference between these three statements.I understand that first and second statements are same, as if(a===b)
gives true
, but the third one will create a object of type number.
我想知道的是这些方法是如何不同的,以及任何方法一个人会优先于另一个?
What I want to know is how these methods are different, and any advantages one will give over the other?
推荐答案
像 1
这样的值是原始的,而不是对象。 JavaScript通常会在必要时将数字提升为 Number
对象。很少有理由明确地构建一个,并且肯定没有特别的优势。也没有理由像 Number(1)
,尽管 Number
构造函数是强制执行的几种方法之一价值是一个数字。
A value like 1
is a primitive, not an object. JavaScript will generally promote numbers to Number
objects when necessary. There's rarely a reason to explicitly construct one, and there's certainly no particular "advantage". There's also no reason for something like Number(1)
, though the Number
constructor is one of several ways of coercing a value to be a number.
这篇关于Javascript以不同的方式声明数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!