Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

实现(5).add(3).minus(2)功能

Sunny-117 opened this issue · comments

commented
commented
(function() {
  function check(x) { //统一转成数字
     return x = isNaN(x) ? 0 : x - 0
  }

  function add (x) {
     x = check(x)
     return this + x
  }

  function minus (x) {
     x = check(x)
     return this - x
  }
  
  Number.prototype.add = add

  Number.prototype.minus = minus    
})();

console.log((5).add('12').minus('1')) // 16
console.log((5).add(2))  // 7
console.log((5).add('abc').minus('1')) // 4
commented
Number.prototype.add = function(num) {
    return this + (+num);
}
Number.prototype.minus = function(num){
    return this - (+num);
}
console.log((5).add(3).minus(2));
Number.prototype.add = function(...numbs){
    let res = this;
    for (const num of numbs) {
        res += (~~num);
    }
    return res;
}
Number.prototype.minus = function(...numbs){
    let res = this;
    for (const num of numbs) {
        res = Math.min(this, (~~num));
    }
    return res;
}
Number.prototype.add = function(num) {
    return this.valueOf() + num;
};

Number.prototype.minus = function(num) {
    return this.valueOf() - num;
};

console.log((5).add(3).minus(2)); // 输出 6