Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

individual characters treated as string in javascript arguments

I need to write a function that retrieves the last parameter passed into the function. If it's just arguments, it should return the last element. If it's a string, it should return the last character. Arrays should return the last element of the array. My code works for arrays, strings and arguments as long as 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 when the input is a bunch of string arguments.

Test.assertEquals(last('a','b','c','z'), 'z');

returns 'a'

Why are disjoint strings evaluating to true when testing if the arguments are arrays or strings and how can I universaly access the last value of arbitrary parameters?

like image 355
user137717 Avatar asked Jul 04 '26 22:07

user137717


1 Answers

Something like this should do that

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

FIDDLE

like image 124
adeneo Avatar answered Jul 07 '26 11:07

adeneo