Why doesn't .join() work with function arguments?

后端 未结 8 1585
遇见更好的自我
遇见更好的自我 2021-02-01 11:59

Why does this work (returns \"one, two, three\"):

var words = [\'one\', \'two\', \'three\'];
$(\"#main\").append(\'

\' + words.join(\", \") + \'

8条回答
  •  無奈伤痛
    2021-02-01 12:16

    At the moment you can't join array arguments, because they aren't an array, shown here

    so you have to either first turn them into an array like this,

    function f() {
      var args = Array.prototype.slice.call(arguments, f.length);
      return 'the list: ' + args.join(',');
    }
    

    or like this, a bit shorter

    function displayIt() {
      return 'the list: ' + [].join.call(arguments, ',');
    }
    

    if you are using something like babel or a compatible browser to use es6 features, you can also do this using rest arguments.

    function displayIt(...args) {
      return 'the list: ' + args.join(',');
    }
    
    displayIt('111', '222', '333');
    

    which would let you do even cooler stuff like

    function displayIt(start, glue, ...args) {
      return start + args.join(glue);
    }
    
    displayIt('the start: ', '111', '222', '333', ',');
    

提交回复
热议问题