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

后端 未结 8 1443
遇见更好的自我
遇见更好的自我 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:20

    It doesn't work because the arguments object is not an array, although it looks like it. It has no join method:

    >>> var d = function() { return '[' + arguments.join(",") + ']'; }
    >>> d("a", "b", "c")
    TypeError: arguments.join is not a function
    

    To convert arguments to an array, you can do:

    var args = Array.prototype.slice.call(arguments);
    

    Now join will work:

    >>> var d = function() {
      var args = Array.prototype.slice.call(arguments);
      return '[' + args.join(",") + ']';
    }
    >>> d("a", "b", "c");
    "[a,b,c]"
    

    Alternatively, you can use jQuery's makeArray, which will try to turn "almost-arrays" like arguments into arrays:

    var args = $.makeArray(arguments);
    

    Here's what the Mozilla reference (my favorite resource for this sort of thing) has to say about it:

    The arguments object is not an array. It is similar to an array, but does not have any array properties except length. For example, it does not have the pop method. ...

    The arguments object is available only within a function body. Attempting to access the arguments object outside a function declaration results in an error.

提交回复
热议问题