数字和数字对象有什么区别?

时间:2013-09-15 14:05:35

标签: javascript

存储在正常变量中的数字之间有什么区别:

var foo = 5; 

还有一个对象:

var bar = new Number(5);

我可以使用数字对象吗?

3 个答案:

答案 0 :(得分:8)

我认为在实践中这两者之间没有区别。数字对象的所有可用方法也可用于原始数字。在基元编号上调用方法时,该数字会临时转换为对象,然后执行该方法。请参阅以下示例:

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

答案 1 :(得分:5)

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

答案 2 :(得分:2)

var foo = 5; 
typeof(foo); // Is Number

var bar = new Number(5);
typeof(bar); // Is object

当您在JavaScript中进入高级级别时,您拥有某些无法在数字上调用的对象属性,因此您需要绘制一条线并查看在哪里使用。

  

数字 - 例如5,3e + 10(所有数字都表现为浮点数 - 显着   用于除法,但可以被x>>>截断0)。有时盒装。   装箱时的号码实例

     

对象 - 例如{foo:'bar',bif:[1,2]},这真的很公正   哈希表。总是盒装。 对象实例。