developer tip

JavaScript에서 기본 부울 값을 설정하는 방법은 무엇입니까?

optionbox 2020. 12. 29. 06:59
반응형

JavaScript에서 기본 부울 값을 설정하는 방법은 무엇입니까?


JavaScript에서 기본 옵션 값 설정은 일반적으로 ||문자 를 통해 수행됩니다.

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

var myCar = new Car();
console.log(myCar.color); // 'blue'

var myOtherCar = new Car('yellow');
console.log(myOtherCar.color); // 'yellow'

작동하기 때문이 color이다 undefinedundefined || String항상입니다 String. 또한 주변의 다른 방식으로 작동 물론 String || undefined이다 String. 두 때 Strings존재하는 첫 번째 승리는 'this' || 'that'것입니다 'this'. 이 같은 다른 방법으로 주위 작동하지 않습니다 'that' || 'this'이다 'that'.

질문은 : 부울 값으로 어떻게 똑같이 얻을 수 있습니까?

다음 예를 들어

var Car = function(hasWheels) {
  this.hasWheels = hasWheels || true;
}

var myCar = new Car();
console.log(myCar.hasWheels); // true

var myOtherCar = new Car(false)
console.log(myOtherCar.hasWheels); // ALSO true !!!!!!

들어 myCar있기 때문에 작품 undefined || true이다 true그러나 당신이 볼 수 있듯이이 작동하지 않습니다 myOtherCar때문 false || true입니다 true. 순서를 변경해 true || false도 여전히 도움이되지 않습니다 true.

따라서 여기에 뭔가가 누락되었거나 다음이 기본값을 설정하는 유일한 방법입니까?

this.hasWheels = (hasWheels === false) ? false: true

건배!


다음과 같이 할 수 있습니다.

this.hasWheels = hasWheels !== false;

그것은 명시 적으로 true때를 제외하고 값을 얻습니다 . ( 및을 포함한 다른 허위 값 은 결과가 되는데, 이것이 당신이 원하는 것이라고 생각합니다.)hasWheelsfalsenullundefinedtrue


어때 :

this.hasWheels = (typeof hasWheels !== 'undefined') ? hasWheels : true;

다른 옵션은 다음과 같습니다.

this.hasWheels = arguments.length > 0 ? hasWheels : true;

ECMA6에서 기본 기능 매개 변수 기능을 사용할 수 있습니다 . 오늘날 ECMA6는 여전히 브라우저에서 완전히 지원되지는 않지만 babel 을 사용하고 새로운 기능을 바로 사용할 수 있습니다.

따라서 원래 예제는 다음과 같이 간단 해집니다.

// specify default value for the hasWheels parameter
var Car = function(hasWheels = true) {
  this.hasWheels = hasWheels;
}

var myCar = new Car();
console.log(myCar.hasWheels); // true

var myOtherCar = new Car(false)
console.log(myOtherCar.hasWheels); // false

게시 된 답변에서 주목해야 할 변형이 있습니다.

var Var = function( value ) {
    this.value0 = value !== false;
    this.value1 = value !== false && value !== 'false';
    this.value2 = arguments.length <= 0 ? true : arguments[0];
    this.value3 = arguments[0] === undefined ? true : arguments[0];
    this.value4 = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
};

                     value0   value1   value2        value3         value4
---------------------------------------------------------------------------
Var("")              true     true     true          true           true
Var("''")            true     true     ''            ''             ''
Var("0")             true     true     0             0              0
Var("'0'")           true     true     '0'           '0'            '0'
Var("NaN")           true     true     NaN           NaN            NaN
Var("'NaN'")         true     true     'NaN'         'NaN'          'NaN'
Var("null")          true     true     null          null           null
Var("'null'")        true     true     'null'        'null'         'null'
Var("undefined")     true     true     undefined     true           true
Var("'undefined'")   true     true     'undefined'   'undefined'    'undefined'
Var("true")          true     true     true          true           true
Var("'true'")        true     true     'true'        'true'         'true'
Var("false")         false    false    false         false          false
Var("'false'")       true     false    'false'       'false'        'false'
  • value1 is made especially from value0 for string 'false' if one needs it to be boolean false. I found this relaxation useful occationally.
  • value2 and value3 are modifications of original posted answers for consistency, without changed results.
  • value4 is how Babel compiles for default parameters.

ReferenceURL : https://stackoverflow.com/questions/15464169/how-to-set-default-boolean-values-in-javascript

반응형