问题答案 12026年6月12日 18:47
Get the last item in an array
To retrieve the last item of an array in JavaScript, we can use the property of the array to access the last element. Here's a simple example:To retrieve the last item of this array, we can use the following code:In this example, returns the length of the array, which is 5. Since array indices start at 0, the index of the last element is , which is 4. This approach effectively retrieves the last item of the array.Additionally, if we want this operation to be more flexible and general, we can encapsulate it into a function:This function first checks if the array is empty; if it is, it returns , otherwise it returns the last item of the array. This makes the code more robust and better suited for various input scenarios.