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"  //结果无空格

  

 

 

posted @ 2015-09-14 13:43  luckymore  阅读(367)  评论(0编辑  收藏  举报