0

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);
asked Oct 31, 2014 at 4:23
1
  • can you give an example of what is giving you the error Commented Oct 31, 2014 at 4:29

2 Answers 2

2

Look at the "arguments" object. So something like

function last(list) {
 if (arguments.length > 1) {
 return arguments[arguments.length-1];
 }
 else {
 ... (as now)
 }
answered Oct 31, 2014 at 4:29
Sign up to request clarification or add additional context in comments.

2 Comments

if the argument is a single array, will arguments[arguments.length-1] return the last value of the array or a reference to the array?
if the argument itself is [1, 2, 3], arguments[arguments.length-1] will return [1, 2, 3], not the values inside
1

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

answered Oct 31, 2014 at 4:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.