写得更好:var arr = [];比var arr = new Array();? [英] Is it better to write: var arr=[]; than var arr=new Array();?

查看:76
本文介绍了写得更好:var arr = [];比var arr = new Array();?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写字是否更好

var arr=[]; then var arr=new Array(); 
var obj={}; then var obj=new Object();

如果是,为什么?

我阅读了幻灯片第36页关于这个想法,但没有给出解释或示例为什么它更好。

I read slide lection page 36 about that idea, but no explanation was given or example why its better.

推荐答案

没有太大的区别在这些定义之间,除了第一种方式使用数组/对象文字,第二种方式使用数组/对象构造函数。

There is not a big difference between these definitions, except that the first way uses the array/object literal and the second the array/object constructor.

数组构造函数可能返回不同的结果,具体取决于传入的参数数量。如果传入一个参数,则会创建一个新的空数组,该数组的长度为该参数。例如:

The array constructor may return different results, depending on the number of arguments passed in. If you pass in one argument, a new empty array is created of the length of that argument. For example:

// arr1 is the same as arr2
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];

alert(arr1.length == arr2.length); // true
alert(arr1[0]); // 1
alert(arr2[0]); // 1

但是,传入一个参数的结果不同:

But, passing in one argument results differently:

// arr3 has length 200 and is empty, while arr4 has length 1 and contains a number
var arr3 = new Array(200);
var arr4 = [200];

alert(arr3.length == arr4.length); // false
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200






定义数组的最快方法或者对象当然是文字方式,因为你不需要先调用构造函数。无论如何,实际的速度差异实际上可以忽略不计。


The speediest way to define an array or object is of course the literal way, because you don't need to call the constructor first. Anyway, the actual speed difference is negligible, really.

我做了一个 速度测试 ,其中我定义了20次10000000相同的数组 1,2,3 ,这给了这些结果:

I did a speed test in Chrome 6, in which I defined 20 times 10000000 the same array 1, 2, 3, which gave these results:

Average speed per 10000000 calls
Array Constructor  : 226.55 ms
Array Literal      : 159.1  ms

如您所见,每10000000个数组定义的数组文字快67,45ms。

As you can see, the array literal is 67,45ms faster per 10000000 array definitions.

这篇关于写得更好:var arr = [];比var arr = new Array();?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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