写一个方法获取指定数组中间的值(一个或者两个)
function getMiddleValues(arr) {
if (!Array.isArray(arr)) {
return "Input must be an array."; // Or throw an error: throw new TypeError("Input must be an array.");
}
if (arr.length === 0) {
return []; // Return an empty array if the input array is empty
}
const mid = Math.floor(arr.length / 2);
if (arr.length % 2 === 0) {
// Even number of elements, return two middle values
return [arr[mid - 1], arr[mid]];
} else {
// Odd number of elements, return one middle value
return [arr[mid]];
}
}
// Examples
console.log(getMiddleValues([1, 2, 3, 4, 5])); // Output: [3]
console.log(getMiddleValues([1, 2, 3, 4])); // Output: [2, 3]
console.log(getMiddleValues([])); // Output: []
console.log(getMiddleValues("not an array")); // Output: "Input must be an array."
This function handles several cases:
- Input Validation: Checks if the input is an array and returns an informative message if not. Consider throwing an error instead of returning a string if you want to stop execution.
- Empty Array: Handles the case where the input array is empty, returning an empty array.
- Odd Length: Returns the single middle element.
- Even Length: Returns the two middle elements.
This improved version is more robust and handles edge cases gracefully. It's generally good practice to validate inputs and handle potential errors to make your functions more reliable.