【问题标题】:how does new Number(value) work in js? [duplicate]new Number(value) 在 js 中是如何工作的? [复制]
【发布时间】:2013-06-17 11:15:59
【问题描述】:
<script>
var num = new Number(43);
console.log(num);
</script>

根据这里的教程:http://www.w3schools.com/jsref/jsref_obj_number.asp

Syntax
var num = new Number(value);
Note: If the value parameter cannot be converted into a number, it returns NaN (Not-a-Number).

问题:

在 firebug->console 中,它显示:Number {},不是我期望的Number {43},无论我输入什么数字new Number(value);它总是显示:Number {} 那么使用new Number(value) 的目的是什么?它是如何工作的?顺便说一句,我在网上搜索了一下,但没有找到很好的解释。

【问题讨论】:

标签: javascript


【解决方案1】:

Number(43) 是一个数字原语,但new Number(43) 将从该数字原语创建一个对象。显示 Number {} 就是 Chrome 控制台显示这样的对象的方式。

new Number(43) 仍然会像数字一样“表现”。在控制台中:

var num = new Number(43); // Number {}
num == 43 // true
num + 5 // 48
num === 43 // false, since the types don't match.

有关new 工作原理的更多信息:How does the new operator work in JavaScript?。如果您只想要一个数字原语,请不要使用new

【讨论】:

    【解决方案2】:

    数字原语和数字对象之间是有区别的。当您使用new 关键字时,您会创建一个新的数字对象,这就是您所看到的。可以通过valueOf获取数字对象的值,返回原语:

    > var n = new Number(42);
    > n.valueOf()
    42
    

    【讨论】:

    • 那么'42'作为属性存储在数字对象中吗?
    • @user2294256:不像n.something = 12 这样的属性,但是是的,有点。
    • 这一行运行后: var n = new Number(42);有没有办法可以看到对象 Number 中的内容是什么?我想看看“42”是如何存储在对象编号中的?
    • @user2294256:你不能。 Number 在本机代码中实现。
    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多