当我需要声明一个新的数组时,我使用这个符号
var arr = new Array();但是当在线测试时,例如在jsbin上 ,一个警告告诉我“使用数组文字符号[]”。
我没有找到避免使用构造函数的原因。 在某种程度上比使用[]吗? 还是坏习惯?
有没有一个很好的理由使用var arr = []; 而不是var arr = new Array(); ?
When I need 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 []."
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 a = []因为Douglas Crockford这样说 。
他的原因包括new 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注意,没有办法使用new Array()创建一个只有一个预先指定的数组元素的数组!
使用[]实际上更有效率, 更安全 ! 可以覆盖Array构造函数并使其做奇怪的事情,但是不能覆盖[]的行为。
就个人而言,我总是使用[]语法,并且总是使用{}语法代替new Object() 。
Mostly, people use var a = [] because Douglas Crockford says so.
His reasons include the non-intuitive and inconsistent behaviour of new 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 itNote that there's no way with new Array() to create an array with just one pre-specified number element in it!
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 [].
Personally, I always use the [] syntax, and similarly always use {} syntax in place of new Object().
更多推荐
发布评论