【问题标题】:What is the difference between a number and a number object?数字和数字对象有什么区别?
【发布时间】:2013-09-19 17:35:00
【问题描述】:

普通变量中存储的数字有什么区别:

var foo = 5; 

还有一个数字对象:

var bar = new Number(5);

我可以使用数字对象做什么?

【问题讨论】:

  • 能否请您发布示例。数字就是数字,无论它们是否包含在对象中。
  • 我说的是对象编号,比如 var num = new Number(123);
  • 编辑问题以澄清...
  • 类似,关于字符串:stackoverflow.com/a/17256340/268093

标签: javascript


【解决方案1】:

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

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

【讨论】:

  • "我认为实际上这两者之间没有区别" foo = new Number(5); bar = new Number(5); console.log(foo === bar) 的行为与 foo = 5; bar = 5; console.log(foo === bar) 完全不同,因为两个不同的 对象 是不相等,而具有相同值的两个数字基元 - 是。
【解决方案2】:

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

【讨论】:

  • 但是这个答案与 OP 在上面的评论中发布的 new Number(123) 有什么关系? (我知道评论是在这个答案之后发布的,所以这当然不是你的错 FaceOfJock,但现在问题已经得到澄清,这并没有真正回答它。)
  • 问题已由版主编辑,不是操作问题
  • @FaceOfJock 评论来自 OP,但我确实编辑了这个问题,因为它非常不清楚。
  • @MarcelGwerder 到现在为止,我认为这就是区别,他只需在示例中将 x 参数替换为 123 并进行测试
【解决方案3】:
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]},这真的只是 哈希表。总是盒装。 对象的实例。

【讨论】:

  • " JavaScript 中的高级级别,你有一些你不能在数字上调用的对象的属性" - 你能举一两个例子吗?
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 2019-03-19
  • 2021-02-14
  • 2012-03-14
  • 1970-01-01
  • 2011-10-30
  • 2016-01-24
相关资源
最近更新 更多