Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  199] [ 3]  / answers: 1 / hits: 44098  / 14 Years ago, tue, january 19, 2010, 12:00:00

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):



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?


More From » jquery

 Answers
5

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.



[#97802] Thursday, January 14, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandt

Total Points: 43
Total Questions: 90
Total Answers: 111

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
;