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


Something like this should do it

function last(){
    var a = arguments;
    return (a.length > 1 ? [].slice.call(a) :
            typeof a[0] === 'string' ? a[0].split('') : a[0]).pop();
}

      



FIDDLE

+1


source


Change the function call to Test.assertEquals(last(['a','b','c','z']), 'z');



Whereas before you passed four different arguments to last()

, this passes a single argument of four characters.

0


source


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







All Articles