javascript - 声明 JavaScript 数组时 "Array()"和 "[]"有什么区别?

标签 javascript arrays declaration

这样声明数组的真正区别是什么:

var myArray = new Array();

var myArray = [];

最佳答案

有区别,但在那个例子中没有区别。

使用更详细的方法: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

;

另一个区别是,当使用 new Array() 时,您可以设置数组的大小,这会影响堆栈大小。如果您遇到堆栈溢出( Performance of Array.push vs Array.unshift ),这可能很有用,这是当数组大小超过堆栈大小时发生的情况,并且必须重新创建它。所以实际上,根据用例,使用 new Array() 可以提高性能,因为您可以防止发生溢出。

正如 this answer 中指出的那样, new Array(5) 实际上不会将五个 undefined 项添加到数组中。它只是为五个项目增加了空间。请注意,以这种方式使用 Array 会导致难以依赖 array.length 进行计算。

关于javascript - 声明 JavaScript 数组时 "Array()"和 "[]"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/931872/

相关文章:

java - netbeans 6.* 中的解析延迟

javascript - Angular - 观察影响子 DOM 元素可见性的祖先中的 ngShow/ngHide 变化

javascript - Linting jsx-a11y 向 div 元素添加角色

javascript - 父组件可以获取mixin数据,但子组件不能获取

arrays - 在R中的三维数组中将n维加在一起

c++ - 错误 : 'object' was not declared in this scope

Javascript 数组范围以及将 js 数组转换为 php 数组

c++ - C++过滤掉数组中的重复值

c++ - 在 C++ 的各种文件中多次包含一个类

c++ - 我不明白 [dcl.fct.default]/3 中的最后一句