在JavaScript中使用[]而不是新的Array()的优点 [英] Advantages of using [] over new Array() in JavaScript

查看:68
本文介绍了在JavaScript中使用[]而不是新的Array()的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用

var foo = []; 

使用

var bar = new Array();

我被告知在新的Array()上使用[]但从来没有多少解释

i've been told to use [] over new Array() but never with much explanation

推荐答案

使用 [] 的主要原因,而不是 new Array()是您传递的参数。当您使用 new Array(10)时,您创建一个包含10个元素的空数组,但是当您使用 [10] ,您创建一个数组,其中一个元素的值为 10 。由于这通常是大多数程序员想要传递给数组的信息(因为数组在Javascript中是动态的),这通常被认为是最佳实践。另外 new Array(10,20)的工作方式与 new Array(10)的工作方式不同。在这种情况下,你具有与 [10,20] 相同的效果,即创建一个包含2个元素10和20的数组。因为这是......奇怪的是...通过传递 new Array()只有一个值,很容易意外地创建一个空数组。 [] 总是有相同的效果,所以我也建议坚持下去。

The main reason to use [] as opposed to new Array() is the arguments you pass. When you use new Array(10), you create an empty array with 10 elements, but when you use [10], you create an array with one element who's value is 10. Since this is generally the information most programmers want to pass to an array (as arrays are dynamic in Javascript), this is generally considered the best practice. Also new Array(10,20) works differently than new Array(10). In this case you have the same effect as [10,20] which is to create an array with 2 elements, 10 and 20. Since this is... strange at best... it's easy to accidentally create an empty array by passing new Array() only one value. [] always has the same effect, so I'd also recommend sticking with it.

这篇关于在JavaScript中使用[]而不是新的Array()的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆