Javascript : optional parameters in function

This question already has an answer here:

  • Is there a better way to do optional function parameters in JavaScript? [duplicate] 29 answers

  • Any unfilled argument will be undefined .

    concatenate(a, c) is equivalent to concatenate(a, b) . You cannot pass the third parameter without passing the second; but you can pass undefined (or null , I suppose) explicitly: concatenate(a, undefined, c) .

    In the function, you can check for undefined and replace with a default value.

    Alternately, you can use an object argument to imitate keyword arguments: concatenate({a: a, c: c}) .


    只需使用arguments数组对象:

    function concatenate() {
      var result = '';
      for (var i = 0; i < arguments.length; i++) {
        result += arguments[i];
      }
      return result;
    }
    

    Use the ES6 rest parameters syntax to get an array of arguments. Then simply join its items to retrieve the concatenated string.

    concatenate(a);
    concatenate(a, b);
    concatenate(a, c);
    
    function concatenate(...args){
      // for old browsers
      // `...args` is an equivalent of `[].slice.call(arguments);`
      return args.join('');
    }
    
    链接地址: http://www.djcxy.com/p/17276.html

    上一篇: 如何将默认值添加到JavaScript函数变量?

    下一篇: Javascript:可选参数在函数中