What's wrong with var x = new Array();

隐身守侯 提交于 2019-11-26 13:22:48
Shog9

Crockford doesn't like new. Therefore, JSLint expects you to avoid it when possible. And creating a new array object is possible without using new....

It's safer to use [] than it is to use new Array(), because you can actually override the value of Array in JavaScript:

Array = function() { };

var x = new Array();
// x is now an Object instead of an Array.

In other words, [] is unambiguous.

Parris

It seems like you can get different performance based on which you are using and for what purpose depending on browser or environment:

http://jsperf.com/new-array-vs-literal/11 ( [1,.2] vs new Array(1,.2) ) the literal is way faster in this circumstance.

http://jsperf.com/new-array-vs-literal/7 ( new Array(500000) vs [].length(500000) ) new Array is faster in chrome v21 it seems for this test by about 7% or 30%) depending on what you do.

Nothing wrong with either form, but you usually see literals used wherever possible-

var s='' is not more correct than var s=new String()....

There's nothing wrong with the first syntax per se. In fact, on w3schools, it lists new Array() as the way to create an array. The problem is that this is the "old way." The "new way", [] is shorter, and allows you to initialize values in the array, as in ["foo", "bar"]. Most developers prefer [] to new Array() in terms of good style.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!