js封裝方法:獲取最大值最小值,排除空數據和異常數據

 //增加數組原型方法寫法
    Array.prototype.getMax = function() {
      if (!this.length) return 0;
      let t = parseFloat(this[0] || 0);
      for (let i = 0; i < this.length; i++) {
        let e = parseFloat(this[i] || 0);
        if (Object.is(e, NaN)) {
          continue;
        }
        if (e > t) {
          t = e;
        }
      }
      return t;
    };
    // 工具js方法
    const getMin = function(arr) {
      if (!arr.length) return 0;
      let t = parseFloat(arr[0] || 0);
      for (let i = 0; i < arr.length; i++) {
        let e = parseFloat(arr[i] || 0);
        if (Object.is(e, NaN)) {
          continue;
        }
        if (e < t) {
          t = e;
        }
      }
      return t;
    };
    let arr = [2, 45, 89, 90, 67, null, "", undefined, NaN, 100, 3, -1];
    console.log(arr.getMax()); // 100
    console.log(getMin(arr)); // -1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章