Javascript 为什么 .join() 不适用于函数参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2091138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't .join() work with function arguments?
提问by Edward Tanguay
Why does this work (returns "one, two, three"):
为什么这样做(返回“一、二、三”):
var words = ['one', 'two', 'three'];
$("#main").append('<p>' + words.join(", ") + '</p>');
and this work (returns "the list: 111"):
和这项工作(返回“列表:111”):
var displayIt = function() {
return 'the list: ' + arguments[0];
}
$("#main").append('<p>' + displayIt('111', '222', '333') + '</p>');
but not this (returns blank):
但不是这个(返回空白):
var displayIt = function() {
return 'the list: ' + arguments.join(",");
}
$("#main").append('<p>' + displayIt('111', '222', '333') + '</p>');
What do I have to do to my "arguments" variable to be to use .join() on it?
我必须对我的“参数”变量做什么才能在其上使用 .join() ?
回答by John Feminella
It doesn't work because the argumentsobject is not an array, although it looks like it. It has no joinmethod:
它不起作用,因为arguments对象不是数组,尽管它看起来像。它没有join方法:
>>> var d = function() { return '[' + arguments.join(",") + ']'; }
>>> d("a", "b", "c")
TypeError: arguments.join is not a function
To convert argumentsto an array, you can do:
要转换arguments为数组,您可以执行以下操作:
var args = Array.prototype.slice.call(arguments);
Now joinwill work:
现在join将工作:
>>> 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 argumentsinto arrays:
或者,您可以使用 jQuery 的makeArray,它会尝试将“几乎数组”之类的arguments变成数组:
var args = $.makeArray(arguments);
Here's what the Mozilla reference(my favorite resource for this sort of thing) has to say about it:
以下是Mozilla 参考资料(我最喜欢的此类资源)对此的评论:
The
argumentsobject is not an array. It is similar to an array, but does not have any array properties exceptlength. For example, it does not have the pop method. ...The
argumentsobject is available only within a function body. Attempting to access the arguments object outside a function declaration results in an error.
该
arguments对象不是数组。它类似于数组,但除了length. 例如,它没有 pop 方法。...该
arguments对象仅在函数体内可用。尝试在函数声明之外访问参数对象会导致错误。
回答by CMS
If you are not interested on other Array.prototypemethods, and you want simply to use join, you can invoke it directly, without converting it to an array:
如果您对其他Array.prototype方法不感兴趣,而只想使用join,则可以直接调用它,而无需将其转换为数组:
var displayIt = function() {
return 'the list: ' + Array.prototype.join.call(arguments, ',');
};
Also you might find useful to know that the comma is the default separator, if you don't define a separator, by specthe comma will be used.
此外,您可能会发现逗号是默认分隔符很有用,如果您未定义分隔符,则根据规范将使用逗号。
回答by SpYk3HH
You could use this jQuery .joinObj Extension/PluginI made.
您可以使用我制作的这个jQuery .joinObj 扩展/插件。
As you'll see in that fiddle, you can use it as follows:
正如您将在该小提琴中看到的那样,您可以按如下方式使用它:
$.joinObj(args, ",");
or
或者
$.(args).joinObj(",");
Plugin Code:
插件代码:
(function(c){c.joinObj||(c.extend({joinObj:function(a,d){var b="";if("string"===typeof d)for(x in a)switch(typeof a[x]){case "function":break;case "object":var e=c.joinObj(a[x],d);e!=__proto__&&(b+=""!=b?d+e:e);break;default:"selector"!=x&&"context"!=x&&"length"!=x&&"jquery"!=x&&(b+=""!=b?d+a[x]:a[x])}return b}}),c.fn.extend({joinObj:function(a){return"object"===typeof this&&"string"===typeof a?c.joinObj(this,a):c(this)}}))})(jQuery);
回答by Doug Neiner
Just use the jQuery utility function makeArray
只需使用 jQuery 实用程序功能 makeArray
argumentsis not an Array, it is an object. But, since it so "array-like", you can call the jQuery utility function makeArrayto make it work:
arguments不是数组,它是一个对象。但是,由于它如此“类似数组”,您可以调用 jQuery 实用程序函数makeArray使其工作:
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>
回答by Peter McG
You can use typeof to see what's happening here:
您可以使用 typeof 来查看这里发生了什么:
>>> 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.
在这里您可以看到 typeof 在两种情况下都返回“object”,但只有一个对象定义了连接函数。
回答by Ryan White
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 babelor a compatible browser to use es6 features, you can also do this using rest arguments.
如果您使用babel或兼容浏览器之类的东西来使用 es6 功能,您也可以使用 rest 参数来做到这一点。
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', ',');
回答by Bernardo Amorim
I don't know if there's a simple way to convert arguments into an array, but you can try this:
我不知道是否有一种简单的方法可以将参数转换为数组,但您可以试试这个:
var toreturn = "the list:";
for(i = 0; i < arguments.length; i++)
{
if(i != 0) { toreturn += ", "; }
toreturn += arguments[i];
}
回答by Kevin Conner
argumentsis not a jQuery object, just a regular JavaScript object. Extend it before you try to call .join(). I think you would write:
arguments不是一个 jQuery 对象,只是一个普通的 JavaScript 对象。在您尝试调用之前扩展它.join()。我想你会写:
return 'the list:' + $(arguments)[0];
(I'm not too familiar with jQuery, only Prototype, so I hope this is not completely bogus.)
(我不太熟悉 jQuery,只熟悉 Prototype,所以我希望这不是完全虚假的。)
Edit: It's wrong! But in his response, Doug Neiner describes what I'm trying to accomplish.
编辑:错了!但在他的回应中,Doug Neiner 描述了我正在努力实现的目标。

