新号码()与号码()

编程入门 行业动态 更新时间:2024-10-11 17:24:03
本文介绍了新号码()与号码()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

新号码()和号码()之间有什么区别?我得到 new Number()创建一个 Number 对象和 Number()只是一个函数,但我应该何时调用哪个,为什么?

What is the difference between new Number() and Number()? I get that new Number() creates a Number object and Number() is just a function, but when should I call which, and why?

在相关的说明中,Mozilla说:

On a related note, Mozilla says:

不要使用Boolean对象将非布尔值转换为布尔值。相反,使用布尔值作为函数来执行此任务。

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task. x = Boolean(expression); // preferred x = new Boolean(expression); // don't use

为什么会这样?我认为结果是一样的?

Why is that? I thought the results were the same?

推荐答案

布尔(表达式)将表达式简单地转换为 布尔原始值 ,而 new Boolean(表达式)将创建转换后的布尔值周围的包装器对象 。

Boolean(expression) will simply convert the expression into a boolean primitive value, while new Boolean(expression) will create a wrapper object around the converted boolean value.

可以看出差异:

// Note I'm using strict-equals new Boolean("true") === true; // false Boolean("true") === true; // true

还有这个(感谢@hobbs):

And also with this (thanks @hobbs):

typeof new Boolean("true"); // "object" typeof Boolean("true"); // "boolean"

注意: 虽然包装器对象会在必要时自动转换为原语(反之亦然),但只有一种情况我可以想到你想要使用的地方 new Boolean ,或原语的任何其他包装器 - 如果要将属性附加到单个值。例如:

Note: While the wrapper object will get converted to the primitive automatically when necessary (and vice versa), there is only one case I can think of where you would want to use new Boolean, or any of the other wrappers for primitives - if you want to attach properties to a single value. E.g:

var b = new Boolean(true); b.relatedMessage = "this should be true initially"; alert(b.relatedMessage); // will work var b = true; b.relatedMessage = "this should be true initially"; alert(b.relatedMessage); // undefined

更多推荐

新号码()与号码()

本文发布于:2023-11-29 14:04:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:号码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!