在Javascript中声明数组时最好的做法是什么?(What are the best practices to follow when declaring an array in Javascri

编程入门 行业动态 更新时间:2024-10-25 10:24:01
在Javascript中声明数组时最好的做法是什么?(What are the best practices to follow when declaring an array in Javascript?)

当我需要声明一个新的数组时,我使用这个符号

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 it

Note 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().

更多推荐

本文发布于:2023-08-07 08:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最好的   数组   做法   声明   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!