codewars算法题-Sum without highest and lowest number

本文介绍了一个简单的算法,用于计算数组中除最大值和最小值外的所有元素之和,并提供了JavaScript实现示例。

算法要求

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值