from the comments, I think you mean you want to either return the last element in an array, the last character in a string, or the last argument passed if multiple arguments were passed. This would do it:
function last() {
if (arguments.length > 1) { // first we handle the case of multiple arguments
return Array.prototype.pop.call(arguments);
}
value = arguments[0]
if (typeof value === 'string') { // next, let's handle strings
return value.split('').pop();
}
if (Object.prototype.toString.call( [] ) === '[object Array]') {// Arrays are of type object in js, so we need to do a weird check
return value.pop();
}
}
arguments
is a pseudo-array that contains all arguments passed into the function, so for last(1,2,3,4,5)
, arguments
would be roughly [1,2,3,4,5]
. It's not exactly that though, because arguments
has all args in order and a length property, but it's prototype isn't Array
, so it isn't truly [1,2,3,4,5]
and lacks all of array's functions. This is why we need to call pop
in the context of arguments
(in javascript, Function.prototype.call
calls the function passing the first arguments as the value of this, and all the rest of the arguments into the arguments
pseudo-array, so for example last.call([], 1, 2, 3)
would call last
in the context of a new array and with arguments
roughly equal to [1,2,3]
).
the rest of the code is pretty straightforward, except for the check to see if value
is an array, which is further explained here.
Finally, pop is an array method that removes the last element from an array and returns it.