How to set default boolean values in JavaScript?

后端 未结 5 1594
执念已碎
执念已碎 2021-01-31 01:38

Setting default optional values in JavaScript is usually done via the || character

var Car = function(color) {
  this.color = color || \'blue\';
};
         


        
5条回答
  •  眼角桃花
    2021-01-31 02:12

    You can do this:

    this.hasWheels = hasWheels !== false;
    

    That gets you a true value except when hasWheels is explicitly false. (Other falsy values, including null and undefined, will result in true, which I think is what you want.)

提交回复
热议问题