![声明JavaScript数组时,“ Array()”和“ []”之间有什么区别?,第1张 声明JavaScript数组时,“ Array()”和“ []”之间有什么区别?,第1张](/aiimages/%E5%A3%B0%E6%98%8EJavaScript%E6%95%B0%E7%BB%84%E6%97%B6%EF%BC%8C%E2%80%9C+Array%EF%BC%88%EF%BC%89%E2%80%9D%E5%92%8C%E2%80%9C+%5B%5D%E2%80%9D%E4%B9%8B%E9%97%B4%E6%9C%89%E4%BB%80%E4%B9%88%E5%8C%BA%E5%88%AB%EF%BC%9F.png)
有所不同,但在该示例中没有区别。
使用更冗长的方法:
new Array()在参数中确实有一个额外的选择:如果将数字传递给构造函数,则将获得该长度的数组:
x = new Array(5);alert(x.length); // 5
为了说明创建数组的不同方法:
var a = [], // these are the same b = new Array(), // a and b are arrays with length 0 c = ['foo', 'bar'],// these are the same d = new Array('foo', 'bar'), // c and d are arrays with 2 strings // these are different: e = [3] // e.length == 1, e[0] == 3 f = new Array(3), // f.length == 3, f[0] == undefined;另一个区别是,使用时,
newArray()您可以设置数组的大小,这会影响堆栈的大小。如果您遇到堆栈溢出(Array.push与Array.unshift的性能)(当数组的大小超过堆栈的大小并必须重新创建它时会发生这种情况),这将很有用。因此,实际上,根据使用情况,使用时
newArray()可以提高性能,因为可以防止发生溢出。
如该答案所指出的,
newArray(5)实际上不会将五个
undefined项目添加到数组中。它只是增加了五个项目的空间。请注意,使用
Array这种方式很难依靠它来
array.length进行计算。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)