在 JavaScript 中使用 {} 或 new Object() 创建一个空对象? [英] Create an empty object in JavaScript with {} or new Object()?

查看:48
本文介绍了在 JavaScript 中使用 {} 或 new Object() 创建一个空对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

推荐答案

对象

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

Objects

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

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

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
      };

数组

对于数组,类似地,使用 new Array(); 而不是 []; 几乎没有任何好处——只有一个小例外:

Arrays

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

var emptyArray = new Array(100);

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

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!').

  1. 永远不要使用 new Object(); - 它比 {}; 更笨拙,而且看起来很傻.
  2. 始终使用 []; - 除非您需要快速创建具有预定义长度的空"数组.
  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 中使用 {} 或 new Object() 创建一个空对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆