arrays - get element from arbitrary list in javascript -
i have function in javascript need retrieve lastly element of list. list can array, string, list in numbers (not array). tried converting list string , array , retrieving index, that's not working.
here code tried:
function last(list){ var array = new string(list); array = array.split(""); homecoming array[array.length-1]; }
i don't understand problem because test suite says expected: 5 instead got: 5 using code wars , did not write tests. expecting number , getting string '5' ? don't understand types in loosely typed languages yet.
from comments, think mean want either homecoming lastly element in array, lastly character in string, or lastly argument passed if multiple arguments passed. it:
function last() { if (arguments.length > 1) { // first handle case of multiple arguments homecoming array.prototype.pop.call(arguments); } value = arguments[0] if (typeof value === 'string') { // next, let's handle strings homecoming value.split('').pop(); } if (object.prototype.tostring.call( [] ) === '[object array]') {// arrays of type object in js, need weird check homecoming value.pop(); } }
arguments
pseudo-array contains arguments passed function, last(1,2,3,4,5)
, arguments
[1,2,3,4,5]
. it's not though, because arguments
has args in order , length property, it's prototype isn't array
, isn't [1,2,3,4,5]
, lacks of array's functions. why need phone call pop
in context of arguments
(in javascript, function.prototype.call
calls function passing first arguments value of this, , rest of arguments arguments
pseudo-array, illustration last.call([], 1, 2, 3)
phone call last
in context of new array , arguments
equal [1,2,3]
).
the rest of code pretty straightforward, except check see if value
array, farther explained here.
finally, pop array method removes lastly element array , returns it.
javascript arrays data-type-conversion
No comments:
Post a Comment