문제

이 질문은 이미 있는 대답을 여기:

나는 항상 처리 선택 자바 스크립트에서 매개 변수 this:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  // Do stuff
}

더 좋은 방법이 있을까요?

이 있는 경우 사용 || 과 같은 것입니다 실패하는가?

도움이 되었습니까?

해결책

OptionalArg가 통과되면 논리가 실패하지만 거짓으로 평가합니다. 대안으로 시도해보십시오.

if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }

또는 대체 관용구 :

optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;

어떤 관용구가 당신에게 가장 좋은 의도를 전달하는지 사용하십시오!

다른 팁

ECMAScript 2015 (일명 "ES6")에서는 함수 선언에서 기본 인수 값을 선언 할 수 있습니다.

function myFunc(requiredArg, optionalArg = 'defaultValue') {
    // do stuff
}

그들에 대해 더 많이 MDN에 관한이 기사.

이것은 현재입니다 Firefox에서만 지원합니다, 그러나 표준이 완료됨에 따라 지원이 빠르게 향상 될 것으로 기대합니다.

편집 (2019-06-12) :

기본 매개 변수는 이제 최신 브라우저에서 널리 지원됩니다. 모든 버전의 Internet Explorer는이 기능을 지원하지 않습니다. 그러나 Chrome, Firefox 및 Edge는 현재이를 지원합니다.

이는 가장 간단 읽을 수 있는 방법:

if (typeof myVariable === 'undefined') { myVariable = 'default'; }
//use myVariable here

폴 딕슨의 답변(에서 내 소견)미만 읽을 수 있는 것보다 이지만,그것은 환경에 온다.

insin 의 대답은 훨씬 더 많은 고급지만 훨씬 더 유용한 큰 함수!

편집 11/17/2013 9:33: 내가 만든 패키지 Node.js 는 보다 쉽게"과"기능(방법)라 파라미터.

문자를 쓰러 뜨려야한다면 NULL 그러면 몇 가지 문제가있을 수 있습니다. 그 외에도, 나는 당신이 아마도 올바른 길을 가고 있다고 생각합니다.

어떤 사람들이 선택한 다른 방법은 인수 목록을 통해 반복되는 변수 배열을 취하는 것입니다. 약간 깔끔해 보이지만 조금 (아주 작은) 프로세스/메모리 집약적이라는 것을 상상합니다.

function myFunction (argArray) {
    var defaults = {
        'arg1'  :   "value 1",
        'arg2'  :   "value 2",
        'arg3'  :   "value 3",
        'arg4'  :   "value 4"
    }

    for(var i in defaults) 
        if(typeof argArray[i] == "undefined") 
               argArray[i] = defaults[i];

    // ...
}

이상적으로는 객체를 전달하기 위해 리팩터링하고 병합 기본 오브젝트가 있으므로 인수가 통과되는 순서는 중요하지 않습니다 (아래 답변의 두 번째 섹션 참조).

그러나 빠르고 신뢰할 수 있고 사용하기 쉽고 부피가 크지 않은 것을 원한다면 다음과 같이 시도하십시오.


수많은 기본 인수에 대한 깨끗한 빠른 수정

  • 우아하게 스케일링 : 각각의 새로운 기본값에 대한 최소 추가 코드
  • 어디서나 붙여 넣을 수 있습니다 : 필요한 args와 변수의 수를 변경하십시오.
  • 당신이 통과하고 싶다면 undefined 기본값을 가진 인수로, 이런 식으로 변수는 다음과 같이 설정됩니다. undefined. 이 페이지의 대부분의 다른 옵션이 대체됩니다 undefined 기본값으로.

다음은 세 가지 선택 인수에 대한 기본값을 제공하는 예입니다 (두 가지 필수 인수 포함)

function myFunc( requiredA, requiredB,  optionalA, optionalB, optionalC ) {

  switch (arguments.length - 2) { // 2 is the number of required arguments
    case 0:  optionalA = 'Some default';
    case 1:  optionalB = 'Another default';
    case 2:  optionalC = 'Some other default';
    // no breaks between cases: each case implies the next cases are also needed
  }

}

간단한 데모. 이것은 비슷합니다 로빙의 대답, 그러나 몇 가지 기본 인수에 대해 쉽게 확장 할 수 있고, 업데이트하기 쉽고, 사용 arguments ~ 아니다 Function.arguments.


더 많은 유연성을 위해 객체를 통과하고 병합합니다

위의 코드는 기본 인수를 수행하는 여러 가지 방법과 마찬가지로 인수를 시퀀스에서 전달할 수 없습니다. optionalC 그러나 떠난다 optionalB 기본값으로 돌아갑니다.

이를위한 좋은 옵션은 객체를 전달하고 기본 객체와 병합하는 것입니다. 이것은 또한 유지 관리에 적합합니다 (코드를 읽을 수 있도록주의를 기울이므로 향후 협력자는 전달한 객체의 가능한 내용에 대해 추측하지 않을 것입니다).

jQuery를 사용하는 예. jQuery를 사용하지 않으면 대신 밑줄을 사용할 수 있습니다. _.defaults(object, defaults) 또는 이 옵션을 찾아보십시오:

function myFunc( args ) {
  var defaults = {
    optionalA: 'Some default',
    optionalB: 'Another default',
    optionalC: 'Some other default'
  };
  args = $.extend({}, defaults, args);
}

여기에 있습니다 행동중인 간단한 예.

이를 위해 몇 가지 다른 체계를 사용할 수 있습니다. 나는 항상 인수를 테스트했습니다.

function myFunc(requiredArg, optionalArg){
  optionalArg = myFunc.arguments.length<2 ? 'defaultValue' : optionalArg;

  ...

- 그렇게하면 실패 할 수는 없지만, 당신의 길이 실패 할 가능성이 있는지 모르겠습니다. 이제는 실제로 실패 할 시나리오를 생각할 수 없습니다 ...

그리고 Paul은 실패한 시나리오를 제공했습니다!-)

Oli의 답변과 유사하게, 나는 인수 객체와 기본값을 정의하는 객체를 사용합니다. 약간 설탕으로 ...

/**
 * Updates an object's properties with other objects' properties. All
 * additional non-falsy arguments will have their properties copied to the
 * destination object, in the order given.
 */
function extend(dest) {
  for (var i = 1, l = arguments.length; i < l; i++) {
    var src = arguments[i]
    if (!src) {
      continue
    }
    for (var property in src) {
      if (src.hasOwnProperty(property)) {
        dest[property] = src[property]
      }
    }
  }
  return dest
}

/**
 * Inherit another function's prototype without invoking the function.
 */
function inherits(child, parent) {
  var F = function() {}
  F.prototype = parent.prototype
  child.prototype = new F()
  child.prototype.constructor = child
  return child
}

... 이것은 조금 더 멋지게 만들 수 있습니다.

function Field(kwargs) {
  kwargs = extend({
    required: true, widget: null, label: null, initial: null,
    helpText: null, errorMessages: null
  }, kwargs)
  this.required = kwargs.required
  this.label = kwargs.label
  this.initial = kwargs.initial
  // ...and so on...
}

function CharField(kwargs) {
  kwargs = extend({
    maxLength: null, minLength: null
  }, kwargs)
  this.maxLength = kwargs.maxLength
  this.minLength = kwargs.minLength
  Field.call(this, kwargs)
}
inherits(CharField, Field)

이 방법의 장점은 무엇입니까?

  • 원하는만큼의 인수를 생략 할 수 있습니다. 하나의 인수의 가치 만 무시하고 싶다면 명시 적으로 통과하지 않고 해당 인수를 제공 할 수 있습니다. undefined 5 개의 인수가 있다고 말하면 마지막 인수 만 제안한 다른 방법과 관련하여 마지막 인수 만 사용자 정의하고 싶을 때.
  • 다른 것과 상속되는 객체에 대한 생성자 함수로 작업 할 때, 생성자 서명에서 해당 인수를 지정할 필요가 없기 때문에 상속하는 객체의 생성자가 요구하는 인수를 쉽게 받아 들일 수 있습니다. 또는 자신의 기본값을 제공합니다 (위에서 볼 수 있듯이 부모 객체의 생성자가 귀하를 위해 그렇게하도록하십시오. CharField 전화 Field의 생성자).
  • 상속 계층의 자식 객체는 부모 생성자가 적합하다고 생각되는대로 부모 생성자에 대한 인수를 사용자 정의하거나 자신의 기본값을 시행하거나 특정 값이 언제나 사용됩니다.

기본값을 광범위하게 사용하는 경우 훨씬 더 읽기 쉬운 것 같습니다.

function usageExemple(a,b,c,d){
    //defaults
    a=defaultValue(a,1);
    b=defaultValue(b,2);
    c=defaultValue(c,4);
    d=defaultValue(d,8);

    var x = a+b+c+d;
    return x;
}

이 기능을 글로벌 ESCOPE에서 선언하십시오.

function defaultValue(variable,defaultValue){
    return(typeof variable!=='undefined')?(variable):(defaultValue);
}

사용 패턴 fruit = defaultValue(fruit,'Apple');

*PS 이름을 바꿀 수 있습니다 defaultValue 짧은 이름으로 기능하면 사용하지 마십시오 default JavaScript의 예약 된 단어입니다.

느슨한 유형 확인

쓰기 쉽지만 0, '', false, null 그리고 undefined 기본값으로 변환되며 결과가 예상되지 않을 수 있습니다.

function myFunc(requiredArg, optionalArg) {
    optionalArg = optionalArg || 'defaultValue';
}

엄격한 유형 확인

더 길지만 대부분의 사례를 다룹니다. 기본값을 잘못 할당하는 경우 유일한 경우가 통과 할 때입니다. undefined 매개 변수로.

function myFunc(requiredArg, optionalArg) {
    optionalArg = typeof optionalArg !== 'undefined' ? optionalArg : 'defaultValue';
}

인수 변수 확인

모든 사례를 포착하지만 글을 쓰는 가장 서투른 것입니다.

function myFunc(requiredArg, optionalArg1, optionalArg2) {
    optionalArg1 = arguments.length > 1 ? optionalArg1 : 'defaultValue';
    optionalArg2 = arguments.length > 2 ? optionalArg2 : 'defaultValue';
}

ES6

불행히도 이것은 현재 브라우저 지원이 매우 열악합니다.

function myFunc(requiredArg, optionalArg = 'defaultValue') {

}

ES2015/ES6을 사용하면 활용할 수 있습니다 Object.assign 교체 할 수 있습니다 $.extend() 또는 _.defaults()

function myFunc(requiredArg, options = {}) {
  const defaults = {
    message: 'Hello',
    color: 'red',
    importance: 1
  };

  const settings = Object.assign({}, defaults, options);

  // do stuff
}

이와 같은 기본 인수를 사용할 수도 있습니다

function myFunc(requiredArg, { message: 'Hello', color: 'red', importance: 1 } = {}) {
  // do stuff
}

선택 변수 처리에 대한 몇 가지 기본 변형을 보는 데 익숙합니다. 때로는 편안한 버전이 유용합니다.

function foo(a, b, c) {
  a = a || "default";   // Matches 0, "", null, undefined, NaN, false.
  a || (a = "default"); // Matches 0, "", null, undefined, NaN, false.

  if (b == null) { b = "default"; } // Matches null, undefined.

  if (typeof c === "undefined") { c = "default"; } // Matches undefined.
}

변수와 함께 사용되는 거짓 기본값 a 예를 들어, 광범위하게 사용됩니다 backbone.js.

사용하는 경우 밑줄 도서관 (당신은 멋진 도서관입니다) :

_.defaults(optionalArg, 'defaultValue');

이 질문에 착륙하여 검색했습니다 ECMAScript 2015의 기본 매개 변수, 그러므로 그냥 언급하는 ...

와 함께 ES6 우리는 할 수 있습니다 기본 매개 변수:

function doSomething(optionalParam = "defaultValue"){
    console.log(optionalParam);//not required to check for falsy values
}

doSomething(); //"defaultValue"
doSomething("myvalue"); //"myvalue"

프로젝트 중에 나는 선택적 매개 변수와 설정으로 너무 많이 반복하고 있음을 알았으므로 유형 확인을 처리하고 기본값을 할당하여 깔끔하고 읽을 수있는 코드를 초래하는 클래스를 만들었습니다. 예제를보고 이것이 당신에게 효과가 있는지 알려주십시오.

var myCar           = new Car('VW', {gearbox:'automatic', options:['radio', 'airbags 2x']});
var myOtherCar      = new Car('Toyota');

function Car(brand, settings) {
    this.brand      = brand;

    // readable and adjustable code
    settings        = DefaultValue.object(settings, {});
    this.wheels     = DefaultValue.number(settings.wheels, 4);
    this.hasBreaks  = DefaultValue.bool(settings.hasBreaks, true);
    this.gearbox    = DefaultValue.string(settings.gearbox, 'manual');
    this.options    = DefaultValue.array(settings.options, []);

    // instead of doing this the hard way
    settings        = settings || {};
    this.wheels     = (!isNaN(settings.wheels)) ? settings.wheels : 4;
    this.hasBreaks  = (typeof settings.hasBreaks !== 'undefined') ? (settings.hasBreaks === true) : true;
    this.gearbox    = (typeof settings.gearbox === 'string') ? settings.gearbox : 'manual';
    this.options    = (typeof settings.options !== 'undefined' && Array.isArray(settings.options)) ? settings.options : [];
}

이 수업 사용 :

(function(ns) {

    var DefaultValue = {

        object: function(input, defaultValue) {
            if (typeof defaultValue !== 'object') throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined') ? input : defaultValue;
        },

        bool: function(input, defaultValue) {
            if (typeof defaultValue !== 'boolean') throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined') ? (input === true) : defaultValue;
        },

        number: function(input, defaultValue) {
            if (isNaN(defaultValue)) throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined' && !isNaN(input)) ? parseFloat(input) : defaultValue;
        },

        // wrap the input in an array if it is not undefined and not an array, for your convenience
        array: function(input, defaultValue) {
            if (typeof defaultValue === 'undefined') throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined') ? (Array.isArray(input) ? input : [input]) : defaultValue;
        },

        string: function(input, defaultValue) {
            if (typeof defaultValue !== 'string') throw new Error('invalid defaultValue type');
            return (typeof input === 'string') ? input : defaultValue;
        },

    };

    ns.DefaultValue = DefaultValue;

}(this));

왜 @Paul의 답장이 다운되었는지 모르겠지만 null 좋은 선택입니다. 어쩌면 더 긍정적 인 예가 더 잘 이해 될 것입니다.

JavaScript에서 놓친 매개 변수는 초기화되지 않은 선언 된 변수와 같습니다 ( var a1;). 그리고 평등 연산자는 정의되지 않은 것을 null로 변환하므로 값 유형과 객체 모두에서 잘 작동하므로 Coffeescript가 선택적인 매개 변수를 처리하는 방법입니다.

function overLoad(p1){
    alert(p1 == null); // Caution, don't use the strict comparison: === won't work.
    alert(typeof p1 === 'undefined');
}

overLoad(); // true, true
overLoad(undefined); // true, true. Yes, undefined is treated as null for equality operator.
overLoad(10); // false, false


function overLoad(p1){
    if (p1 == null) p1 = 'default value goes here...';
    //...
}

그러나 최고의 의미론은 typeof variable === 'undefined' 약간 더 좋습니다. 기능이 어떻게 구현되는지 근본적인 API의 문제이기 때문에 이것을 방어하려고하지 않습니다. API 사용자에게 관심을 가져서는 안됩니다.

또한 여기에 물리적으로 어떤 논증이 누락되었는지 확인하는 유일한 방법이 있다고 덧붙여 야합니다. in 불행히도 매개 변수 이름으로 작동하지 않는 연산자이므로 인덱스를 전달해야합니다. arguments.

function foo(a, b) {
    // Both a and b will evaluate to undefined when used in an expression
    alert(a); // undefined
    alert(b); // undefined

    alert("0" in arguments); // true
    alert("1" in arguments); // false
}

foo (undefined);

Undefined에 대한 테스트는 불필요하며 user568458이 지적했듯이 NULL 또는 FALSE가 통과되면 제공된 솔루션이 실패하기 때문에 강력하지 않습니다. API 사용자는 False 또는 Null이 해당 매개 변수를 피하도록 강제로 강제 할 것이라고 생각할 수 있습니다.

function PaulDixonSolution(required, optionalArg){
   optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
   console.log(optionalArg);
};
PaulDixonSolution("required");
PaulDixonSolution("required", "provided");
PaulDixonSolution("required", null);
PaulDixonSolution("required", false);

결과는 다음과 같습니다.

defaultValue
provided
null
false

마지막 두 사람은 잠재적으로 나쁘다. 대신 시도해보십시오 :

function bulletproof(required, optionalArg){
   optionalArg = optionalArg ? optionalArg : "defaultValue";;
   console.log(optionalArg);
};
bulletproof("required");
bulletproof("required", "provided");
bulletproof("required", null);
bulletproof("required", false);

결과 :

defaultValue
provided
defaultValue
defaultValue

이것이 최적이 아닌 유일한 시나리오는 실제로 부울이나 의도적 인 널이어야 할 선택적 매개 변수가있을 때입니다.

나는 여기에서 언급 된 몇 가지 옵션을 시도했고 성능을 테스트했습니다. 이 순간 논리가 가장 빠른 것 같습니다. 이것은 시간이 지남에 따라 변화의 대상이지만 (다른 JavaScript 엔진 버전).

이 결과는 내 결과입니다 (Microsoft Edge 20.10240.16384.0) :

Function executed            Operations/sec     Statistics
TypeofFunction('test');          92,169,505     ±1.55%   9% slower
SwitchFuntion('test');            2,904,685     ±2.91%  97% slower
ObjectFunction({param1: 'test'});   924,753     ±1.71%  99% slower
LogicalOrFunction('test');      101,205,173     ±0.92%     fastest
TypeofFunction2('test');         35,636,836     ±0.59%  65% slower

이 성능 테스트는 다음에서 쉽게 복제 할 수 있습니다.http://jsperf.com/optional-parameters-typeof-vs-switch/2

이것은 테스트 코드입니다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
    Benchmark.prototype.setup = function() {
        function TypeofFunction(param1, optParam1, optParam2, optParam3) {
            optParam1 = (typeof optParam1 === "undefined") ? "Some default" : optParam1;
            optParam2 = (typeof optParam2 === "undefined") ? "Another default" : optParam2;
            optParam3 = (typeof optParam3 === "undefined") ? "Some other default" : optParam3;
        }

        function TypeofFunction2(param1, optParam1, optParam2, optParam3) {
            optParam1 = defaultValue(optParam1, "Some default");
            optParam2 = defaultValue(optParam2, "Another default");
            optParam3 = defaultValue(optParam3, "Some other default");
        }

        function defaultValue(variable, defaultValue) {
            return (typeof variable !== 'undefined') ? (variable) : (defaultValue);
        }

        function SwitchFuntion(param1, optParam1, optParam2, optParam3) {
            switch (arguments.length - 1) { // <-- 1 is number of required arguments
                case 0:
                    optParam1 = 'Some default';
                case 1:
                    optParam2 = 'Another default';
                case 2:
                    optParam3 = 'Some other default';
            }
        }

        function ObjectFunction(args) {
            var defaults = {
                optParam1: 'Some default',
                optParam2: 'Another default',
                optParam3: 'Some other default'
            }
            args = $.extend({}, defaults, args);
        }

        function LogicalOrFunction(param1, optParam1, optParam2, optParam3) {
            optParam1 || (optParam1 = 'Some default');
            optParam2 || (optParam1 = 'Another default');
            optParam3 || (optParam1 = 'Some other default');
        }
    };
</script>

이것이 내가 끝난 것입니다.

function WhoLikesCake(options) {
  options = options || {};
  var defaultOptions = {
    a : options.a || "Huh?",
    b : options.b || "I don't like cake."
  }
  console.log('a: ' + defaultOptions.b + ' - b: ' + defaultOptions.b);

  // Do more stuff here ...
}

다음과 같이 호출 :

WhoLikesCake({ b : "I do" });

사람들 -

이들 및 기타 솔루션을 살펴본 후 원래 W3Schools의 코드 스 니펫을 사용하여 여러 솔루션을 사용해 보았습니다. 다음에서 작동하는 것을 찾을 수 있습니다. 각 항목은 댓글을 달았으며 개별 의견을 제거하여 간단히 실험 할 수있는 방법입니다. 명확하게 말하면, 정의되지 않은 "Eyecolor"매개 변수입니다.

function person(firstname, lastname, age, eyecolor)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
// if(null==eyecolor)
//   this.eyecolor = "unknown1";
//if(typeof(eyecolor)==='undefined') 
//   this.eyecolor = "unknown2";
// if(!eyecolor)
//   this.eyecolor = "unknown3";
this.eyecolor = this.eyecolor || "unknown4";
}

var myFather = new person("John", "Doe", 60);
var myMother = new person("Sally", "Rally", 48, "green");

var elem = document.getElementById("demo");
elem.innerHTML = "My father " +
              myFather.firstname + " " +
              myFather.lastname + " is " +
              myFather.age + " with " +
              myFather.eyecolor + " eyes.<br/>" +
              "My mother " +
              myMother.firstname + " " +
              myMother.lastname + " is " +
              myMother.age + " with " +
              myMother.eyecolor + " eyes."; 
function Default(variable, new_value)
{
    if(new_value === undefined) { return (variable === undefined) ? null : variable; }
    return (variable === undefined) ? new_value : variable;
}

var a = 2, b = "hello", c = true, d;

var test = Default(a, 0),
test2 = Default(b, "Hi"),
test3 = Default(c, false),
test4 = Default(d, "Hello world");

window.alert(test + "\n" + test2 + "\n" + test3 + "\n" + test4);

http://jsfiddle.net/mq60hqrf/

여기 내 해결책이 있습니다. 이것으로 원하는 매개 변수를 남길 수 있습니다. 선택적 매개 변수의 순서는 중요하지 않으며 사용자 정의 검증을 추가 할 수 있습니다.

function YourFunction(optionalArguments) {
            //var scope = this;

            //set the defaults
            var _value1 = 'defaultValue1';
            var _value2 = 'defaultValue2';
            var _value3 = null;
            var _value4 = false;

            //check the optional arguments if they are set to override defaults...
            if (typeof optionalArguments !== 'undefined') {

                if (typeof optionalArguments.param1 !== 'undefined')
                    _value1 = optionalArguments.param1;

                if (typeof optionalArguments.param2 !== 'undefined')
                    _value2 = optionalArguments.param2;

                if (typeof optionalArguments.param3 !== 'undefined')
                    _value3 = optionalArguments.param3;

                if (typeof optionalArguments.param4 !== 'undefined')
                    //use custom parameter validation if needed, in this case for javascript boolean
                   _value4 = (optionalArguments.param4 === true || optionalArguments.param4 === 'true');
            }

            console.log('value summary of function call:');
            console.log('value1: ' + _value1);
            console.log('value2: ' + _value2);
            console.log('value3: ' + _value3);
            console.log('value4: ' + _value4);
            console.log('');
        }


        //call your function in any way you want. You can leave parameters. Order is not important. Here some examples:
        YourFunction({
            param1: 'yourGivenValue1',
            param2: 'yourGivenValue2',
            param3: 'yourGivenValue3',
            param4: true,
        });

        //order is not important
        YourFunction({
            param4: false,
            param1: 'yourGivenValue1',
            param2: 'yourGivenValue2',
        });

        //uses all default values
        YourFunction();

        //keeps value4 false, because not a valid value is given
        YourFunction({
            param4: 'not a valid bool'
        });
  1. arg || 'default' 좋은 방법이며 사례의 90%에서 일합니다.

  2. '거짓'일 수있는 값을 전달해야 할 때 실패합니다.

    • false
    • 0
    • NaN
    • ""

    이 경우 좀 더 장황하고 확인해야합니다. undefined

  3. 또한 선택적인 인수가있을 때 조심하십시오. 모든 인수의 유형을 알고 있어야합니다.

옵션 arg가 거짓 인 경우 모든 경우 defaultValue로 끝납니다.

function myFunc(requiredArg, optionalArg) {
    optionalArg = optionalArg || 'defaultValue';
    console.log(optionalArg);
    // Do stuff
}
myFunc(requiredArg);
myFunc(requiredArg, null);
myFunc(requiredArg, undefined);
myFunc(requiredArg, "");
myFunc(requiredArg, 0);
myFunc(requiredArg, false);

6 개는 모두 거짓이기 때문에 위의 모든 로그 기본값이 있습니다. 사례 4, 5, 6에서는 옵션 arg를 DefaultValue로 설정하는 데 관심이 없지만 거짓이기 때문에 설정됩니다.

내가 틀렸다면 저를 바로 잡으십시오. 그러나 이것은 가장 간단한 방법처럼 보입니다 (어쨌든 하나의 논쟁의 경우) :

function myFunction(Required,Optional)
{
    if (arguments.length<2) Optional = "Default";
    //Your code
}

그 것들은 Typeof 운영자 버전보다 짧습니다.

function foo(a, b) {
    a !== undefined || (a = 'defaultA');
    if(b === undefined) b = 'defaultB';
    ...
}

나는 당신이 사용하는 것이 좋습니다 논쟁 이 방법:

function myFunc(){
  arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'})

  //do stuff, using arguments.requiredArg and arguments.optionalArg
  //    to access your arguments

}

당신은 또한 교체 할 수 있습니다 undefined 다음과 같이받을 것으로 예상되는 주장의 유형에 따라

function myFunc(){
  arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'})

  //do stuff, using arguments.requiredArg and arguments.optionalArg
  //    to access your arguments

}

그것은 보인다는 가장 안전한 방법을 다루는 모든\모든 falsy 유형 의 공급 인수 결정하기 전에 사용 기본 -이를 확인하기 위해 존재\의 존재 선택 사항 인수 에서 호출되는 기능입니다.

에 의존하는 인수 개체의 회원이 생성되지 않도 얻을 만든 경우에 인수가 누락,사실에 관계없이 될 수 있다는 선언을 작성할 수 있습니다 당신의 기능은 다음과 같다:

  function myFunc(requiredArg, optionalArg){
        optionalArg = 1 in arguments ? optionalArg : 'defaultValue';
  //do stuff
  }

이를 활용하여 행동:우리가 안전하게 확인을 위해 누락된 모든 값을 인수에 목록을 임의로 명시적으로 할 때마다 우리는지 확인해야 함을 얻는 특정 값에 대한 절차입니다.

에서 다음과 같은 데모드 의도적으로 넣 형식 없 undefined 기본값으로 할 수 있는지 여부를 확인에 실패할 수 있습니다 falsy 인수 값은 0 으로 거짓 etc., 는 경우 예상대로 작동합니다.

function argCheck( arg1, arg2, arg3 ){

       arg1 = 0 in arguments || undefined;
       arg2 = 1 in arguments || false;
       arg3 = 2 in arguments || 0;
   var arg4 = 3 in arguments || null;

   console.log( arg1, arg2, arg3, arg4 ) 
}

지금 확인,몇 falsy 인수 값을 보면 자신의 존재가 올바르게 검사하고 따라서 평가 true:

argCheck( "", 0, false, null );
>> true true true true

는 것을 의미-그들은 실패하지 않았다는 인식의/으로 예상되는 인수 값입니다.여기서 우리는 확인과 함께 모든 인수는 누락에 따르면 우리의 algo 습득하는 기본값으로 그 경우에도 falsy.

argCheck( );
>> undefined false 0 null

우리가 볼 수 있듯이,인수 arg1,arg2,arg3 고 선언하지 않는 arg4, 은 자신의 정확한 복귀 기본 값으로 정렬됩니다.기 때문에 우리는 이제 작동하는지 확인,우리는 다시 작성할 수 있습니다 기능하는 것입니다 실제로 그들을 사용할 수 있으로 첫 번째 예에서 사용:나 는 경우삼항 상태입니다.

에서 기능이 있는 하나 이상의 선택수-반복을 통해,수 없는 우리에게 몇 가지 비트입니다.하지만 이후 인수 이름 지 않을 얻을 초기화면에 그들의 값이 제공되지 않을,우리는 그들에 액세스 할 수 있습니다 이름으로 더 이상 경우에도 우리는 프로그래밍 방식으로 작성에 기본값이 우리에만 액세스할 수 있습니다 그들에 의해 arguments[index] 는 쓸모없는 코드를 읽기 쉽도록 현명하다.

하지만 이외에도 불편함에서는 특정 코딩 상황이 될 수 있습 완벽하게 허용,거기에 또 다른 문제는 불명한 여러와 임의의 번호를 인수 기본값으로 초기화합니다.할 수 있는 고려되어야의 버그로,우리는 더 이상 건너뛰 인수,우리가 한번할 수 있게 되었을지 않고 값을 주고,구문에 같은:

argCheck("a",,22,{});

기 때문에 그것을 던져!는 것이 불가능하게 우리를 대체하는 우리의 인수와 함께 특정 falsy 우리가 원하는 기본값이다.는 바,이후 인수를체 열과 같은 개체와 예상되는 이 구문을 지원 및 컨벤션으로,기본적으로 또는 기본!

이 때문에 근시안적인 결정을 우리는 더 이상 소망을 쓰는 함수를 다음과 같다:

function argCheck( ) {
    var _default = [undefined, 0, false, null ],
        _arg = arguments;

 for( var x in _default ) {
         x in _arg ? 1 : _arg[x] = _default[x];
        }
    console.log( _arg[0],_arg[1],_arg[2],_arg[3] );
}

어떤 경우에,우리는 우리를 작성할 수 있는 각 기본값이 원하는 형식의 인수에 행할 수 있는 적어도 그들에 액세스하여 args.인덱스이다.

예를 들면 이 함수를 호출 수확량:

argCheck();
>>undefined 0 false null

에 정의된 대로 우리의 기본값이 배열의 인수 값입니다.그러나 다음과 같은 여전히 가능:

argCheck({})
>>Object {  } 0 false null

argCheck({}, [])
>>Object {  } Array [  ] false null

하지만 유감스럽게도 아닙니다:

 argCheck("a",,,22);
 >>SyntaxError: expected expression, got ','

그렇지 않으면 로그인:

>>a 0 false 22

하지만 그에 더 나은 세상!그러나 원래 질의 최상위 기능은 잘 할 것입니다.예를 들어:

function argCheck( arg, opt ) {
         1 in arguments ? 1 : opt = "default";
         console.log( arg, opt );
}

p.s.:죄송하지 않을 보존하기 유형 의 선택 기본값에 나 인수를 입력하는 동안 그들을 쓰기.

function foo(requiredArg){
  if(arguments.length>1) var optionalArg = arguments[1];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top