Why use {} instead of new Object() and use [] instead of new Array() and true/false instead of new Boolean()?

后端 未结 5 1110
南方客
南方客 2020-12-06 00:55

Many people say that you should avoid new Object, new Array()and instead use {}. [], and true/false.

What are the benefits of using the literal constructs to get a

5条回答
  •  无人及你
    2020-12-06 01:47

    One reason not yet mentioned is the ambiguity when passing parameters to the Array constructor. It's all specified behavior, it's just quirky.

    new Array(1,2,3); // [1,2,3], that's OK
    new Array(1); // [undefined], some may expect to get [1] instead
    

    A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. (See below.) Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Syntax

提交回复
热议问题