简体   繁体   English

Javascript:Function 返回数组的最后一个元素

[英]Javascript: Function returning last element of array

I'm taking Colt Steele's Udemy Course titled: "The Web Developer Bootcamp 2020".我正在参加 Colt Steele 的 Udemy 课程,标题为:“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.练习目标如下:请编写一个名为 lastElement 的 function,它接受一个数组参数。 The function should return the last element of the array(without removing the element). function 应返回数组的最后一个元素(不删除该元素)。 If the array is empty, the function should return null.如果数组为空,则 function 应返回 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.我很想知道为什么我写的 function 不起作用,以及一些关于我应该如何重新考虑 function 以使其起作用的指示。

Best Regards Andreas最好的问候安德烈亚斯

Change to this condition.改成这个状态。

if (num && num.length>0) 

change your condition to:将您的条件更改为:

if(num && num.length>0) 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) 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:问题在于值和值的区别:空数组为真但未定义为假,因此 [],==undefined 为真:但是:

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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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