在 JavaScript 中使用 {} 或 new Object() 创建一个空对象?

发布于 2024-12-03 17:14:01 字数 263 浏览 1 评论 0原文

在 JavaScript 中创建空对象有两种不同的方法:

var objectA = {}
var objectB = new Object()

脚本引擎处理它们的方式有什么不同吗?有什么理由使用其中一种而不是另一种吗?

同样,也可以使用不同的语法创建空数组:

var arrayA = []
var arrayB = new Array()

There are two different ways to create an empty object in JavaScript:

var objectA = {}
var objectB = new Object()

Is there any difference in how the script engine handles them? Is there any reason to use one over the other?

Similarly it is also possible to create an empty array using different syntax:

var arrayA = []
var arrayB = new Array()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

葬心 2024-12-10 17:14:01

对象

使用 new Object() 没有任何好处,而 {} 可以使您的代码更紧凑、更具可读性。

对于定义空对象,它们在技术上是相同的。 {} 语法更短、更简洁(更少 Java 风格),并且允许您立即内联填充对象 - 如下所示:

var myObject = {
  title: 'Frog',
  url: '/img/picture.jpg',
  width: 300,
  height: 200
};

数组

对于数组,同样使用 几乎没有任何好处new Array() 超过 [] — 有一个小例外:

var emptyArray = new Array(100);

创建一个 100 项长的数组,其中所有槽都包含 undefined,这可能在以下情况下很好/有用某些情况(例如(new Array(9)).join('Na-Na') + '蝙蝠侠!')。

我的建议

  1. 永远不要使用 new Object(); — 它比 {} 更笨拙,而且看起来很傻。
  2. 始终使用 [] — 除非您需要快速创建具有预定义长度的“空”数组。

Objects

There is no benefit to using new Object(), whereas {} can make your code more compact, and more readable.

For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:

var myObject = {
  title: 'Frog',
  url: '/img/picture.jpg',
  width: 300,
  height: 200
};

Arrays

For arrays, there's similarly almost no benefit to ever using new Array() over [] — with one minor exception:

var emptyArray = new Array(100);

creates a 100 item long array with all slots containing undefined, which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').

My recommendation

  1. Never use new Object(); — it's clunkier than {} and looks silly.
  2. Always use [] — except when you need to quickly create an "empty" array with a predefined length.

是的,有区别,它们不一样。确实,您会得到相同的结果,但引擎以不同的方式为它们工作。其中一种是对象字面量,另一种是构造函数,这是在 javascript 中创建对象的两种不同方式。

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

在 JS 中,一切都是对象,但是您应该注意 new Object() 的以下事项:它可以接收一个参数,并且根据该参数,它将创建一个字符串、一个数字或只是一个空对象。

例如:new Object(1),将返回一个数字。 new Object("hello") 将返回一个字符串,这意味着对象构造函数可以根据参数将对象创建委托给其他构造函数,如字符串、数字等......这非常重要当你管理动态数据来创建对象时,记住这一点很重要。

许多作者建议,当你可以使用某种文字表示法时,不要使用对象构造函数,这样你就可以确定你正在创建的是什么你期望在你的代码中包含。

我建议您进一步阅读 javascript 上的文字表示法和构造函数之间的差异,以找到更多详细信息。

Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.

For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..

Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.

I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.

卸妝后依然美 2024-12-10 17:14:01

它们具有相同的最终结果,但我想简单地补充一点,使用文字语法可以帮助人们习惯 JSON 语法(JavaScript 文字对象语法的字符串化子集),因此,了解 JSON 语法可能是一种很好的做法。

另一件事:如果您忘记使用 new 运算符,您可能会遇到细微的错误。因此,使用文字将帮助您避免这个问题。

最终,这将取决于情况和偏好。

These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.

不羁少年 2024-12-10 17:14:01
var objectA = {}

速度要快得多,而且根据我的经验,也更常用,因此最好采用“标准”并节省一些打字时间。

var objectA = {}

is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.

陌生 2024-12-10 17:14:01

数组实例化性能

如果您希望创建一个没有长度的数组:

var arr = [];var arr = new Array();

如果你想创建一个特定长度的空数组:

var arr = new Array(x);var arr = []; 更快arr[x-1] = undefined;

对于基准测试,请单击以下内容:https:// /jsfiddle.net/basickarl/ktbbry5b/

但是我不知道两者的内存占用,我可以想象 new Array() 占用更多空间。 >

Array instantiation performance

If you wish to create an array with no length:

var arr = []; is faster than var arr = new Array();

If you wish to create an empty array with a certain length:

var arr = new Array(x); is faster than var arr = []; arr[x-1] = undefined;

For benchmarks click the following: https://jsfiddle.net/basickarl/ktbbry5b/

I do not however know the memory footprint of both, I can imagine that new Array() takes up more space.

錯遇了你 2024-12-10 17:14:01

对象和数组字面量语法 {}/[] 是在 JavaScript 1.2 中引入的,因此在 4.0 之前的 Netscape Navigator 版本中不可用(并且会产生语法错误)。

我的手指仍然默认为 new Array(),但我已经是一个很老的人了。值得庆幸的是,Netscape 3 并不是当今许多人必须考虑的浏览器......

The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...

菊凝晚露 2024-12-10 17:14:01

我相信 此处{} > 作为良好的编码约定。 new 对于伪经典继承是必要的。 var obj = {}; 方式有助于提醒您,这不是一种经典的面向对象语言,而是一种原型语言。因此,您真正需要 new 的唯一时间是当您使用构造函数时。例如:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

然后像这样使用:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

new Object 相比,使用 {} 的另一个优点是您可以使用它来执行 JSON 样式的对象字面量。

I believe {} was recommended in one of the Javascript vids on here as a good coding convention. new is necessary for pseudoclassical inheritance. the var obj = {}; way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new is when you are using constructors functions. For example:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

Then it is used like so:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

Another advantage to using {} as oppose to new Object is you can use it to do JSON-style object literals.

枯寂 2024-12-10 17:14:01
Var Obj = {};

这是最常用、最简单的方法。

使用

var Obj = new Obj() 

不是优选的。

无需使用new Object()

为了简单性、可读性和执行速度,使用第一个(对象字面量方法)。

Var Obj = {};

This is the most used and simplest method.

Using

var Obj = new Obj() 

is not preferred.

There is no need to use new Object().

For simplicity, readability and execution speed, use the first one (the object literal method).

阳光下的泡沫是彩色的 2024-12-10 17:14:01

这本质上是同一件事。使用您认为更方便的任何东西。

This is essentially the same thing. Use whatever you find more convenient.

怪异←思 2024-12-10 17:14:01

好的,同样的事情只有两种不同的方法!一个称为对象文字,另一个是函数构造函数

但请继续阅读,有几件事我想分享:

使用 {} 使您的代码更具可读性,同时创建 Object 或其他内置函数的实例不推荐...

此外,对象函数获取参数,因为它是一个函数,例如 Object(params)...但 {} 是在 JavaScript 中启动对象的纯粹方法...

使用对象文字使您的代码看起来更干净,更易于其他开发人员阅读,而且与 JavaScript 中的最佳实践一致...

虽然 Javascript 中的对象几乎可以是任何东西,但 {} 仅指向 javascript 对象,要测试其工作原理,请在 javascript 代码或控制台中执行以下操作

var n = new Object(1); //Number {[[PrimitiveValue]]: 1}

: ,它正在创建一个数字!

var a = new Object([1,2,3]); //[1, 2, 3]

这是创建一个数组!

var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}

String 的结果很奇怪!

因此,如果您要创建对象,建议使用对象字面量,拥有标准代码并避免像上面那样的任何代码事故,而且根据我的经验,使用 {} 的性能更好!

OK, there are just 2 different ways to do the same thing! One called object literal and the other one is a function constructor!

But read on, there are couple of things I'd like to share:

Using {} makes your code more readable, while creating instances of Object or other built-in functions not recommended...

Also, Object function gets parameters as it's a function, like Object(params)... but {} is pure way to start an object in JavaScript...

Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...

While Object in Javascript can be almost anything, {} only points to javascript objects, for the test how it works, do below in your javascript code or console:

var n = new Object(1); //Number {[[PrimitiveValue]]: 1}

Surprisingly, it's creating a Number!

var a = new Object([1,2,3]); //[1, 2, 3]

And this is creating a Array!

var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}

and this weird result for String!

So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {} is better in my experience!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文