zoukankan      html  css  js  c++  java
  • js提取整数部分,移除首末空格

      给Object.prototype增加方法可使该方法对所有对象可用,这样的方式对函数、数组、字符串、数字、正则表达式和布尔值同样适用。比如说为Function.prototype增加方法来使得改方法对所有函数可用。

      增加method方法是为了不用输入prototype属性。method对所有函数可用

    Function.prototype.method = function(name, func) {
        this.prototype[name] = func;
        return this;
    }  

      1.  用method方法给Number类型添加integer函数来获取数字整数部分。

    Number.method('integer', function(){
    
      return Math[this < 0 ? 'ceil' : 'floor'](this);
    });  

      测试:-10/3 = -3.333333....

    console.log((-10/3).integer());
    > -3  //结果

      2.  移除字符串首末的空格,这其实也是原生js的一个疏忽。

    String.method('trim', function() {
        return this.replace(/^s+|s+$/g, '');
    });
    
    console.log("    trim    ".trim());    //"    trim    "字符串就是trim方法中得this
    > "trim"  //结果无空格
    

      

     

  • 相关阅读:
    [UVa514] Rails
    今日才真正懂了BFS
    [UVa11292] Dragon of Loowater
    [UVa] TEX Quotes
    白书杂七杂八
    [OpenJudge] Feed_Accounting
    [OpenJudge] Jolly_Jumpers
    Restart
    Collection of Websites
    Oracle11完全卸载方法
  • 原文地址:https://www.cnblogs.com/luckythan/p/4806841.html
Copyright © 2011-2022 走看看