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);
-
can you give an example of what is giving you the errorCrayonViolent– CrayonViolent2014年10月31日 04:29:27 +00:00Commented Oct 31, 2014 at 4:29
2 Answers 2
Look at the "arguments" object. So something like
function last(list) {
if (arguments.length > 1) {
return arguments[arguments.length-1];
}
else {
... (as now)
}
2 Comments
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