Reputation: 2175
I need to write a function that returns the last element from the input arguments. This is easy for Strings and Arrays, but the function can also accept a "list of arguments". I have tried to process this list of arguments with String and Array syntax, but I get errors about object not having method x. This is what I have so far:
function last(list){
// return last element of array
if(list instanceof Array){
return list[list.length-1];
}
// return last element of string
else if(typeof list === 'string'){
return list.substring(list.length-1, list.length);
}
}
Is there a way to convert an arbitrary list of arguments to a String or Array? Here is an example of what I mean by list of arguments.
Test.assertEquals(last(1,"b",3,"d",5), 5);
Upvotes: 0
Views: 65
Reputation: 7698
Look at the "arguments" object. So something like
function last(list) {
if (arguments.length > 1) {
return arguments[arguments.length-1];
}
else {
... (as now)
}
Upvotes: 2
Reputation: 507
You can just call arguments[arguments.length -1] inside the function, and it should give you the last argument, regardless of type.
Here's the resource on arguments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
Upvotes: 1