What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

后端 未结 18 1485
生来不讨喜
生来不讨喜 2020-11-21 12:00

What\'s the real difference between declaring an array like this:

var myArray = new Array();

and

var myArray = [];
<         


        
18条回答
  •  -上瘾入骨i
    2020-11-21 12:56

    There's more to this than meets the eye. Most other answers are correct BUT ALSO..

    new Array(n)

    • Allows engine to reallocates space for n elements
    • Optimized for array creation
    • Created array is marked sparse which has the least performant array operations, that's because each index access has to check bounds, see if value exists and walk the prototype chain
    • If array is marked as sparse, there's no way back (at least in V8), it'll always be slower during its lifetime, even if you fill it up with content (packed array) 1ms or 2 hours later, doesn't matter

    [1, 2, 3] || []

    • Created array is marked packed (unless you use delete or [1,,3] syntax)
    • Optimized for array operations (for .., forEach, map, etc)
    • Engine needs to reallocate space as the array grows

    This probably isn't the case for older browser versions/browsers.

提交回复
热议问题