Fork me on GitHub

JS去掉数组中的最大值最小值

    思路:确定数组中最大最小值(排序查找arr.sort()/Math.max()方法)---->确定最大最小值位置(循环遍历)---->移除最大最小值(可借助数组方法splice(i,1))

    主要矛盾是确定数组中的最大值最小值,方法很多,包括但不限于:遍历比较查找、sort()排序查找、Math.max()/min()方法。

    遍历比较查找不难,这里就不讲了,sort排序用法如下,主要需要注意升序还是降序。

let max = arr.sort(function(a,b){

    return b-a; // b-a从大到小,a-b从小到大

})[0];

    

    内置函数Math.max()Math.min()可以找出参数中的最大值和最小值,但对于数字组成的数组是不能用的。但是,Function.prototype.apply()让你可以使用提供的this与参数组成的_数组(array)_来调用函数。给apply()第二个参数传递numbers数组,等于使用数组中的所有值作为函数的参数。还有就是通过基于ES6的方法通过操作展开符实现。

     

let max = Math.max.apply({}, this);
let min = Math.min.apply({}, this);

let max = Math.max(...arr);
let min = Math.min(...arr);

    后面通过循环遍历确定最大最小值位置以及移除最大最小值就很简单了。

   

    接下来我们既可以将以上行为封装在函数中,也可以对Array原生对象进行扩展。

    1. 对Array原生对象进行扩展----给Array.prototype增加一个delMaxMin方法

Array.prototype.deleMaxMin = function () {
  let max = Math.max.apply({}, this);
  let min = Math.min.apply({}, this);
  for(let i=0; i<this.length;i++) {
    if(this[i] == max)
    {this.splice(i,1)}
    if(this[i] == min)
    {this.splice(i,1)}
 }
  return this;
}

arr = [22, 6, 12, 44, 56, 99, 24, 36, 99, 6]

arr.delMxMin();

// [22, 12, 44, 56, 24, 36]

    注意调用方法形式为 arr.delMxMin(); 

 

    2. 封装在函数体内

function spliceMaxMin (arry){
    let result = arry.splice(0)
    let max = Math.max(...result)
    let min = Math.min(...result)
    for(var i = 0; i < result.length;i++){
        if(result[i] == max){
            result.splice(i,1)
        }
        if(result[i] ==min){
            result.splice(i,1)
        }
    }
    return result
}

arr = [22, 6, 12, 44, 56, 99, 24, 36, 99, 6]
spliceMaxMin (arr);  // [22, 12, 44, 56, 24, 36]

    注意调用方法为 spliceMaxMin (arr); 

 

posted @ 2020-08-14 13:08  Lynn_z  阅读(2671)  评论(0编辑  收藏  举报