js提取整数部分,移除首末空格
给Object.prototype增加方法可使该方法对所有对象可用,这样的方式对函数、数组、字符串、数字、正则表达式和布尔值同样适用。比如说为Function.prototype增加方法来使得改方法对所有函数可用。
增加method方法是为了不用输入prototype属性。method对所有函数可用
1 2 3 4 | Function.prototype.method = function (name, func) { this .prototype[name] = func; return this ; } |
1. 用method方法给Number类型添加integer函数来获取数字整数部分。
1 2 3 4 | Number.method( 'integer' , function (){ return Math[ this < 0 ? 'ceil' : 'floor' ]( this ); }); |
测试:-10/3 = -3.333333....
1 | console.log((-10/3).integer()); |
1 | > -3 //结果 |
2. 移除字符串首末的空格,这其实也是原生js的一个疏忽。
1 2 3 4 5 | String.method( 'trim' , function () { return this .replace(/^\s+|\s+$/g, '' ); }); console.log( " trim " .trim()); //" trim "字符串就是trim方法中得this |
1 | > "trim" //结果无空格 |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步