为什么.join()不使用函数参数?

Edw*_*uay 68 javascript jquery join

为什么这样做(返回"一,二,三"):

var words = ['one', 'two', 'three'];
$("#main").append('<p>' + words.join(", ") + '</p>');
Run Code Online (Sandbox Code Playgroud)

这项工作(返回"列表:111"):

var displayIt = function() {
    return 'the list: ' + arguments[0];
}   
$("#main").append('<p>' + displayIt('111', '222', '333') + '</p>');
Run Code Online (Sandbox Code Playgroud)

但不是这个(返回空白):

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

我必须对我的"arguments"变量做什么才能使用.join()?

Joh*_*lla 89

它不起作用,因为该arguments对象不是一个数组,虽然看起来像它.它没有join方法:

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

要转换arguments为数组,您可以执行以下操作:

var args = Array.prototype.slice.call(arguments);
Run Code Online (Sandbox Code Playgroud)

现在join将工作:

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

或者,您可以使用jQuery makeArray,它将尝试将"几乎数组" arguments转换为数组:

var args = $.makeArray(arguments);
Run Code Online (Sandbox Code Playgroud)

以下是Mozilla引用(我最喜欢的这类资源)必须说明的内容:

arguments对象不是数组.它类似于数组,但除了之外没有任何数组属性 length.例如,它没有pop方法....

arguments对象仅在函数体中可用.尝试访问函数声明之外的arguments对象会导致错误.

  • `Array.prototype.join.call(arguments,',')` (5认同)
  • 或者`Array.join(arguments,",")`(比如`Array.forEach(arguments,func);`) (4认同)
  • @Anonymous TypeError:对象函数Array(){[native code]}没有方法'join' (3认同)

CMS*_*CMS 20

如果您对其他Array.prototype方法不感兴趣,并且只想使用它join,则可以直接调用它,而无需将其转换为数组:

var displayIt = function() {
    return 'the list: ' + Array.prototype.join.call(arguments, ',');
};
Run Code Online (Sandbox Code Playgroud)

另外,您可能会发现逗号是默认分隔符很有用,如果您没有定义分隔符,则通过规范将使用逗号.