写一个方法获取指定数组中间的值(一个或者两个)

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.

posted @   王铁柱6  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示