写一个方法获取指定数组中间的值(一个或者两个)
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具