简体   繁体   English

var x = new Array();怎么了?

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

In JSLint, it warns that 在JSLint中,它警告说

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? 该建议背后的原因是什么?

It's safer to use [] than it is to use new Array() , because you can actually override the value of Array in JavaScript: 使用[]比使用new Array()更安全,因为实际上您可以在JavaScript中覆盖Array的值:

Array = function() { };

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

In other words, [] is unambiguous. 换句话说, []是明确的。

Crockford doesn't like new . 克罗克福德不喜欢new Therefore, JSLint expects you to avoid it when possible. 因此, JSLint希望您尽可能避免使用它 And creating a new array object is possible without using new .... 并且无需使用new ...即可创建新的数组对象。

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/11([1,.2 ] vs new Array(1,.2))在这种情况下,字面量要快得多。

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. http://jsperf.com/new-array-vs-literal/7(new Array(500000)与[] .length(500000))chrome v21中的new Array速度更快,看来此测试的速度约为7%或30 %),具体取决于您的工作。

Nothing wrong with either form, but you usually see literals used wherever possible- 两种形式都没错,但是您通常会尽可能地看到使用的文字,

var s='' is not more correct than var s=new String().... var s =''不比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. 实际上,在w3schools上 ,它列出了new 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"] . [] new way [][]较短,它允许您初始化数组中的值,如["foo", "bar"] Most developers prefer [] to new Array() in terms of good style. 就良好的风格而言,大多数开发人员更喜欢[]new Array()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM