简体   繁体   English

为什么我在 output 以及答案中变得不确定?

[英]Why i am getting undefined in the output along with the answer?

let array = [1, 2, 3];
function lastElement(array) 
{

    if (array === []) 
    {
        return null;
    }
    else 
    {
        return array.slice(-1);
    }
}

you are doing it in the wrong way, you cannot check if an array is empty like you did.您以错误的方式进行操作,您无法像以前那样检查数组是否为空。

function lastElement(array) {
  if(array.length == 0) return null
  return array[array.length - 1]
}

array.length returns the count of elements inside an array. array.length返回数组中元素的计数。

You also need not to add an else statement because if we are returning from a functions, the code below that line does not get executed.您还不需要添加 else 语句,因为如果我们从函数返回,则该行下方的代码不会被执行。

Hi I seen you are facing the issue of checking array and slice the data also.嗨,我看到您也面临检查数组和切片数据的问题。

Simply if you want to check the array is empty or not you will using something like this in the js简单地说,如果你想检查数组是否为空,你将在 js 中使用类似的东西

To get the last element of an array you can use要获取数组的最后一个元素,您可以使用

 let array = [1, 2, 3]; console.log(array.length-1);

To Check array is empty and also get the last element of an array检查数组是否为空并获取数组的最后一个元素

 let array = [1, 2, 3]; function lastElement(array) { if(array.length == 0) return null return array[array.length - 1] } console.log(lastElement(array))

To know more about slice which you have used in the above problem click here要了解有关您在上述问题中使用的切片的更多信息,请单击此处

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

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