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

拈花ヽ惹草 提交于 2019-11-26 03:40:59

问题


In JSLint, it warns that

var x = new Array();

(That\'s not a real variable name) should be

var result = [];

What is wrong with the 1st syntax? What\'s the reasoning behind the suggestion?


回答1:


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....




回答2:


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.




回答3:


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.




回答4:


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

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




回答5:


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.



来源:https://stackoverflow.com/questions/885156/whats-wrong-with-var-x-new-array

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