存储在普通变量中的数字有什么区别:
var foo = 5;
还有一个数字对象:
var bar = new Number(5);
我可以使用数字对象做什么?
我认为在实践中这两者之间没有区别。数字对象的所有可用方法也可用于原始数字。当您对原始数字调用方法时,该数字会暂时转换为对象,然后执行该方法。请参阅以下示例:
var temp1 = Object(1) // number object
var temp2 = 1 // primitive number
console.log(temp1.toString()) // invoke its own method. result: 1
console.log(temp2.toString()) // temporarily converts to object and invoke number object method. result:1
console.log(Object(1).constructor === Number) //true
console.log((1).constructor === Number) //true
// ^---------- temporarily converts to object
一个Number
对象包含一些有用的方法和属性,例如:
Method Description
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number object
Property Description
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
constructor Returns the function that created the Number object's prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object
var foo = 5;
typeof(foo); // Is Number
var bar = new Number(5);
typeof(bar); // Is object
当您深入到 JavaScript 中的高级级别时,您有一些无法在数字上调用的对象的属性,因此您可以画一条线并查看在哪里使用什么。
数字——例如 5、3e+10(所有数字都表现为浮点数——对除法很重要,但可以被 x >>> 0 截断)。有时是盒装的。 装箱时的 Number 实例。
对象——例如 {foo: 'bar', bif: [1, 2]},它们实际上只是哈希表。总是盒装。对象的实例。