JavaScript 中的 var num=30 和 var num=new Number(30) 有什么区别?

编程入门 行业动态 更新时间:2024-10-26 08:29:22
本文介绍了JavaScript 中的 var num=30 和 var num=new Number(30) 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在 JavaScript 中似乎有很多不同的方法可以做同样的事情.在 JavaScript 中使用new"关键字表示数字和只输入数字有什么区别吗?我看不出有什么区别:

It seems like there are so many different ways to do the same things in JavaScript. Is there any difference in using the "new" keyword in JavaScript for numbers and just entering a number? I see no difference between:

var num = 30;

var num = new Number(30);

字符串(和数组)也一样:

It's the same with strings (and arrays):

var str = "hello";

var str = new String("hello");

为什么有人会使用一种方法而不是另一种方法?它们对我来说似乎是一样的,而且只是打字更多.

Why would someone use one method over the other? They seem the same to me, and it's just more typing anyway.

推荐答案

首先创建一个基元.另一个是一个对象.

The first creates a primitive. The other an object.

理论上有区别,但实际上没有区别.当需要成为对象时,JavaScript 引擎会自动装箱一个对象的原语.

In theory there is a difference but in practice none. The JavaScript engine automagicly boxes a primitive to an object when it needs to be an object.

var myPrimitiveNumber = 42;
// calling .toFixed will 'box' the primitive into a number object,
// run the method and then 'unbox' it back to a primitive
console.log( myPrimitiveNumber.toFixed(2) );

我发现的唯一用法是,如果您想从构造函数返回一个原语.

The only usage I've found is if you want to return a primitive from a constructor function.

function Foo() {
    return 42;
}

var foo = new Foo();
console.log(foo); // foo is instance of Foo

function Bar() {
    return new Number(42);
}

var bar = new Bar();
console.log(bar); // bar is instance of Number

这篇关于JavaScript 中的 var num=30 和 var num=new Number(30) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:16:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410202.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   var   JavaScript   num   Number

发布评论

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

>www.elefans.com

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