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

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

问题描述

有两种不同的方式使用JavaScript创建一个空对象:

  VAR对象A = {}
VAR对象B =新的对象()

有没有脚本引擎如何处理它们有什么区别?没有任何理由使用了另一种?

类似地,也可以使用不同的语法来创建一个空数组:

  VAR arrayA = []
VAR arrayB =新的Array()


解决方案

对象

还有就是使用新的对象()没有任何益处; - 而 {}; 可以让你的code的紧凑,更具可读性。

有关定义空对象他们在技术上是相同的。在 {} 语法更短,更简洁(不以Java-ISH),并让你瞬间填充对象内联 - 像这样:

  VAR myObject的= {
        标题:'青蛙',
        网址:'/img/picture.jpg',
        宽度:300,
        身高:200
      };

阵列

有关阵列,还有永远使用新的Array()同样几乎没有好处; []; - - 只有一个小例外:

  VAR emptyArray =新阵列(100);

创建了一个100项多头排列包含所有插槽未定义 - 这可能是在某些情况下漂亮的/有用(如(新阵(9))。加入('娜娜')+'蝙蝠侠!)。

我的建议


  1. 不要使用新的对象(); - 这是klunky,看起来傻傻

  2. 总是使用 []; - 当你需要快速创建一个predefined长度一个空数组除了

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

解决方案

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 klunky and looks silly.
  2. Always use []; -- except when you need to quickly create an "empty" array with a predefined length.

这篇关于在JavaScript中创建一个空的对象,{}或新的对象()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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