JS去掉陣列中的最大值最小值
阿新 • • 發佈:2020-08-14
思路:確定陣列中最大最小值(排序查詢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()
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);