codewars算法題-Sum without highest and lowest number

算法要求

Sum all the numbers of the array (in F# and Haskell you get a list) except the highest and the lowest element (the value, not the index!).(The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!).
If array is empty, null or None, or if only 1 Element exists, return 0

function sumArray(array) {
  if(array==null){
    return 0;
  }else{
    var arrayLen = array.length;
    if(arrayLen==0||arrayLen==1){
      return 0;
    }else {
      var sum = 0;
      for( index in array){
        if(!Number.isNaN(array[index])){
          sum = sum + array[index];
        }
      }
      return sum - Math.max.apply(null, array) - Math.min.apply(null, array);
    }
  }
}

本來不需要加判斷數組元素的,多餘了。
總結: 求數組極值統一方法: Math.max.apply(null, array);

發佈了37 篇原創文章 · 獲贊 9 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章