代码之家  ›  专栏  ›  技术社区  ›  Whirlwind

在Javascript中对特定类型定义静态方法

  •  1
  • Whirlwind  · 技术社区  · 3 年前

    percIncrease(a, b) {
        let percent;
        if (b !== 0) {
          if (a !== 0) {
            percent = ((b - a) / a) * 100;
          } else {
            percent = b * 100;
          }
        } else {
          percent = -a * 100;
        }
        return percent.toFixed(3);
      }
    

    Number.prototype.percIncrease = function (a, b) {
      let percent;
      if (b !== 0) {
        if (a !== 0) {
          percent = ((b - a) / a) * 100;
        } else {
          percent = b * 100;
        }
      } else {
        percent = -a * 100;
      }
      return percent.toFixed(3);
    };
    

    Number.percIncrease(a,b);
    

    myNumber.percIncrease(inCompareToValue: anotherNumber)
    
    3 回复  |  直到 3 年前
        1
  •  2
  •   Nina Scholz    3 年前

    Number.prototype.percIncrease = function(base) {
        let percent;
        if (base) {
            percent = this
                ? (base - this) * 100 / this
                : base * 100;
        } else {
            percent = -this * 100;
        }
        return percent.toFixed(3);
    };
    
    
    console.log(5..percIncrease(4));
        2
  •  1
  •   Barmar    3 年前

    Number.percIncrease = function (a, b) {
      let percent;
      if (b !== 0) {
        if (a !== 0) {
          percent = ((b - a) / a) * 100;
        } else {
          percent = b * 100;
        }
      } else {
        percent = -a * 100;
      }
      return percent.toFixed(3);
    };
    
    console.log(Number.percIncrease(10, 15));
        3
  •  0
  •   Yahya Alami    3 年前

    Number.prototype.percIncrease(1, 10); //"1,10" are examples