Javascript array best practice to use [] instead of new array?

前端 未结 5 1138
醉话见心
醉话见心 2020-12-31 04:08

I read at many tutorials that the current best practices to create a new javascript array is to use

var arr = [] 

instead of



        
5条回答
  •  情深已故
    2020-12-31 04:23

    Usually an array literal(var a=[1,2,3] or a=[]) is the way to go.

    But once in a while you need an array where the length itself is the defining feature of the array.

    var A=Array(n) would (using a literal) need two expressions-

    var A=[]; A.length=n;

    In any event, you do not need the 'new' operator with the Array constructor, not in the way that you DO need 'new' with a new Date object, say.

提交回复
热议问题