【发布时间】:2026-01-20 14:50:01
【问题描述】:
请编写一个名为 lastElement 的函数,它接受单个数组参数。该函数应返回数组的最后一个元素(不删除元素)。如果数组为空,则函数应返回 null。
- lastElement([3,5,7]) //7
- lastElement([1]) //1
- lastElement([]) //null
** the code that I wrote **
let array = [3, 5, 7];
function lastElement (array) {
return array[array.length - 1];
}
我对最后一部分感到困惑,如果数组为空,则函数返回 null。
【问题讨论】:
-
你在 * 上写一个新问题只是为了问“我怎么知道一个数组是否为空”? :|
-
不要让投反对票让你失望。要么你不知道(在这种情况下你来对地方了),要么你有精神障碍,在这种情况下你来对地方了。 :-)
-
如果你想要最简单的初学者:function lastElement(array){ if(array.length === 0){ return null } else { return array[array.length - 1] } }
标签: javascript arrays function