Single characters parsed as string in javascript arguments
I need to write a function that returns the last parameter passed to the function. If they are just arguments, it should return the last item. If it is a string, it should return the last character. Arrays must return the last element of the array. My code works for arrays, strings and arguments if they are not all strings.
function last(list){
var arr;
if(list instanceof Array){
return list[list.length-1];
}
if(typeof list === 'string' || list instanceof String){
arr = list.split("");
return arr[arr.length-1];
}
return arguments[arguments.length-1];
}
This works for almost every case, but I have a problem where the input is a collection of string arguments.
Test.assertEquals(last('a','b','c','z'), 'z');
returns 'a'
Why are strings delimiting true being checked if the arguments are arrays or strings, and how can I universally access the last value of arbitrary parameters?
+3
source to share
3 answers
Change your last function like this:
function last(list){
var arr;
if(list instanceof Array){
return list[list.length-1];
}
if((typeof list === 'string' || list instanceof String) && (arguments.length == 1)){
arr = list.split("");
return arr[arr.length-1];
}
return arguments[arguments.length-1];
};
0
source to share