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

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

    You can use typeof to see what's happening here:

    >>> typeof(['one', 'two', 'three'])
    "object"
    >>> typeof(['one', 'two', 'three'].join)
    "function"
    >>> typeof(arguments)
    "object"
    >>> typeof(arguments.join)
    "undefined"
    

    Here you can see that typeof returns "object" in both cases but only one of the objects has a join function defined.

    0 讨论(0)
  • 2021-02-01 12:41

    Just use the jQuery utility function makeArray

    arguments is not an Array, it is an object. But, since it so "array-like", you can call the jQuery utility function makeArray to make it work:

    var displayIt = function() {
        return 'the list: ' + $.makeArray(arguments).join(",");
    }   
    $("#main").append('<p>' + displayIt('111', '222', '333') + '</p>');
    

    Which will output:

    <p>the list: 111,222,333</p>
    
    0 讨论(0)
提交回复
热议问题