简体   繁体   中英

Javascript: Function returning last element of array

I'm taking Colt Steele's Udemy Course titled: "The Web Developer Bootcamp 2020". I have however become stuck on a certain coding exercise. The exercise objective is as follows: Please write a function called lastElement which accepts a single array argument. The function should return the last element of the array(without removing the element). If the array is empty, the function should return null.

I have tried coming up with a solution but cant seem to figure it out. My current best guess is this:

function lastElement (num) {
if (num !== undefined){
    return num[num.length -1];
} return null;

}

I'm interested in knowing why the function I have written doesn't work and some pointers on how I should rethink the function, so that it does work.

Best Regards Andreas

Change to this condition.

if (num && num.length>0) 

change your condition to:

if(num && num.length>0)

additionally, if they decide to enter an argument that is not an array,

if(num && Array.isArray(num) && num.length>0)

The problem lies in the difference of truthy and falsy values: Empty array is truthy but undefined is falsy, so [],==undefined is true: but:

num[num.length -1]; 

means:

num[-1]; 

which is undefined.

You can use this:

function lastElement(arr) {
if(arr.length>0){
   return arr[arr.length-1];
} else{
   return null;
}
function lastElement(test) {
if (test.length == 0)
    return null;
else
    return test[test.length - 1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM