为什么.join()不使用函数参数? [英] Why doesn't .join() work with function arguments?
问题描述
为什么这样做(返回一,二,三):
Why does this work (returns "one, two, three"):
var words = ['one', 'two', 'three'];
$("#main").append('<p>' + words.join(", ") + '</p>');
这项工作(返回列表:111):
and this work (returns "the list: 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>');
我必须对我的arguments变量做什么才能使用.join ()吗?
推荐答案
它不起作用,因为参数
object不是数组,虽然它看起来像。它没有加入
方法:
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);
现在加入
将起作用:
>>> var d = function() {
var args = Array.prototype.slice.call(arguments);
return '[' + args.join(",") + ']';
}
>>> d("a", "b", "c");
"[a,b,c]"
或者,您可以使用jQuery的 makeArray
,它会尝试将像 arguments
这样的几乎数组转换为数组:
Alternatively, you can use jQuery's makeArray
, which will try to turn "almost-arrays" like arguments
into arrays:
var args = $.makeArray(arguments);
以下是 Mozilla reference (我最喜欢这种东西的资源)不得不说:
Here's what the Mozilla reference (my favorite resource for this sort of thing) has to say about it:
参数
对象不是数组。
它类似于数组,但
没有任何数组属性,除了
length
。例如,pop方法没有
。 ...
The
arguments
object 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. ...
参数
对象在函数体中仅可用
。尝试
访问
函数声明之外的arguments对象会导致
错误。
The arguments
object is available only
within a function body. Attempting to
access the arguments object outside a
function declaration results in an
error.
这篇关于为什么.join()不使用函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!