在Javascript中声明数组时,哪一个是最佳实践? [重复]

时间:2021-07-08 01:31:41

Possible Duplicate:
Create an empty object in JavaScript with {} or new Object()?

可能重复:使用{}或新的Object()在JavaScript中创建一个空对象?

When I want to declare a new array I use this notation

当我想声明一个新数组时,我使用这种表示法

var arr = new Array();

But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []."

但是当在线测试时,例如在jsbin上,警告会向我发出“使用数组文字符号[]”的信号。

I didn't find a reason to avoid using the constructor. Is in some way less efficient than using []? Or is it bad practice?

我没有找到避免使用构造函数的理由。在某种程度上比使用[]效率低吗?还是不好的做法?

Is there a good reason to use var arr = []; instead of var arr = new Array();?

是否有充分的理由使用var arr = [];而不是var arr = new Array();?

5 个解决方案

#1


5  

Mostly, people use var a = [] because Douglas Crockford says so.

大多数情况下,人们使用var a = [],因为Douglas Crockford这样说。

His reasons include the non-intuitive and inconsistent behaviour of new Array():

他的理由包括新的Array()的非直观和不一致的行为:

var a = new Array(5);     // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it

Note that there's no way with new Array() to create an array with just one pre-specified number element in it!

请注意,新的Array()无法创建只包含一个预先指定的数字元素的数组!

Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ].

使用[]实际上更有效,更安全!可以覆盖Array构造函数并使它做奇怪的事情,但你不能覆盖[]的行为。

Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().

就个人而言,我总是使用[]语法,同样总是使用{}语法代替新的Object()。

#2


7  

[] is:

  • shorter
  • clearer
  • not subject to new Array(3) and new Array(3,3) doing completely different things
  • 不受新的Array(3)和新的Array(3,3)的影响

  • cannot be overridden.
  • 不能被覆盖。

Example code:

var a = new Array(3);
var b = new Array(3,3);
Array = function () { return { length: "!" }; };
var c = new Array();
var d = [];
alert(a.length); // 3
alert(b.length); // 2
alert(c.length); // !
alert(d.length);​ // (still) 0​​​​​​​​

This code live - will try to create 4 alerts!

此代码实时 - 将尝试创建4个警报!

#3


0  

The recommended practice is to use

推荐的做法是使用

var arr = [];

Already answered here

已在这里回答

#4


0  

In javascript, you should use literal when you can.

在javascript中,你应该尽可能使用文字。

var a = []; instead of var o = new Array();

var a = [];而不是var o = new Array();

var o = {}; instead of var o = new Object();

var o = {};而不是var o = new Object();

Similarly, don't do new String("abc");, new Number(1);, and so on.

同样,不要做新的String(“abc”);,新的Number(1);等等。

#5


0  

JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays.

JavaScript是一种原型语言,而不是像C#这样的经典语言。尽管JavaScript确实有一个看起来很像C#的新运算符,但您不应该使用它来创建新对象或数组。

//Bad way to declare objects and arrays
var person = new Object(), 
    keys = new Array();

The new keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead.

新关键字被部分添加到语言中以安抚经典语言,但实际上它往往会使开发人员感到困惑而不是帮助他们。相反,JavaScript中存在声明对象和数组的本机方法,您应该使用它们。

Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation.

您应该使用文字表示法来声明对象和数组,而不是使用以前的语法。

//Preferred way to declare objects and arrays
var person = {}, 
    keys = [];

Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax.

使用这种模式,您实际上使用Object Literals和数组初始化器语法具有很强的表达能力。

//Preferred way to declare complex objects and arrays
var person = {
        firstName: "Elijah",
        lastName: "Manor",
        sayFullName: function() {
            console.log( this.firstName + " " + 
                this.lastName );
        }
    }, 
    keys = ["123", "676", "242", "4e3"];

Best Practice

You should declare all of your variables using their literal notation instead of using the new operation. In a similar fashion you shouldn’t use the new keyword for Boolean, Number, String, or Function. All they do is add additional bloat and slow things down.

您应该使用文字符号声明所有变量,而不是使用新操作。以类似的方式,您不应该将new关键字用于Boolean,Number,String或Function。他们所做的只是增加额外的膨胀和缓慢的事情。

The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out Douglas Crockford's post entitled JavaScript, We Hardly new Ya.

使用new关键字的唯一真正原因是,如果要创建新对象并且希望它使用您定义的构造函数。有关此主题的更多信息,您可以查看Douglas Crockford的帖子,题为JavaScript,We Hardly new Ya。

#1


5  

Mostly, people use var a = [] because Douglas Crockford says so.

大多数情况下,人们使用var a = [],因为Douglas Crockford这样说。

His reasons include the non-intuitive and inconsistent behaviour of new Array():

他的理由包括新的Array()的非直观和不一致的行为:

var a = new Array(5);     // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it

Note that there's no way with new Array() to create an array with just one pre-specified number element in it!

请注意,新的Array()无法创建只包含一个预先指定的数字元素的数组!

Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ].

使用[]实际上更有效,更安全!可以覆盖Array构造函数并使它做奇怪的事情,但你不能覆盖[]的行为。

Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().

就个人而言,我总是使用[]语法,同样总是使用{}语法代替新的Object()。

#2


7  

[] is:

  • shorter
  • clearer
  • not subject to new Array(3) and new Array(3,3) doing completely different things
  • 不受新的Array(3)和新的Array(3,3)的影响

  • cannot be overridden.
  • 不能被覆盖。

Example code:

var a = new Array(3);
var b = new Array(3,3);
Array = function () { return { length: "!" }; };
var c = new Array();
var d = [];
alert(a.length); // 3
alert(b.length); // 2
alert(c.length); // !
alert(d.length);​ // (still) 0​​​​​​​​

This code live - will try to create 4 alerts!

此代码实时 - 将尝试创建4个警报!

#3


0  

The recommended practice is to use

推荐的做法是使用

var arr = [];

Already answered here

已在这里回答

#4


0  

In javascript, you should use literal when you can.

在javascript中,你应该尽可能使用文字。

var a = []; instead of var o = new Array();

var a = [];而不是var o = new Array();

var o = {}; instead of var o = new Object();

var o = {};而不是var o = new Object();

Similarly, don't do new String("abc");, new Number(1);, and so on.

同样,不要做新的String(“abc”);,新的Number(1);等等。

#5


0  

JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays.

JavaScript是一种原型语言,而不是像C#这样的经典语言。尽管JavaScript确实有一个看起来很像C#的新运算符,但您不应该使用它来创建新对象或数组。

//Bad way to declare objects and arrays
var person = new Object(), 
    keys = new Array();

The new keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead.

新关键字被部分添加到语言中以安抚经典语言,但实际上它往往会使开发人员感到困惑而不是帮助他们。相反,JavaScript中存在声明对象和数组的本机方法,您应该使用它们。

Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation.

您应该使用文字表示法来声明对象和数组,而不是使用以前的语法。

//Preferred way to declare objects and arrays
var person = {}, 
    keys = [];

Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax.

使用这种模式,您实际上使用Object Literals和数组初始化器语法具有很强的表达能力。

//Preferred way to declare complex objects and arrays
var person = {
        firstName: "Elijah",
        lastName: "Manor",
        sayFullName: function() {
            console.log( this.firstName + " " + 
                this.lastName );
        }
    }, 
    keys = ["123", "676", "242", "4e3"];

Best Practice

You should declare all of your variables using their literal notation instead of using the new operation. In a similar fashion you shouldn’t use the new keyword for Boolean, Number, String, or Function. All they do is add additional bloat and slow things down.

您应该使用文字符号声明所有变量,而不是使用新操作。以类似的方式,您不应该将new关键字用于Boolean,Number,String或Function。他们所做的只是增加额外的膨胀和缓慢的事情。

The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out Douglas Crockford's post entitled JavaScript, We Hardly new Ya.

使用new关键字的唯一真正原因是,如果要创建新对象并且希望它使用您定义的构造函数。有关此主题的更多信息,您可以查看Douglas Crockford的帖子,题为JavaScript,We Hardly new Ya。