在 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!'
).
- 永远不要使用
new Object();
- 它比{};
更笨拙,而且看起来很傻. - 始终使用
[];
- 除非您需要快速创建具有预定义长度的空"数组.
- Never use
new Object();
- it's clunkier than{};
and looks silly. - Always use
[];
- except when you need to quickly create an "empty" array with a predefined length.