什么是扩展内置对象的有用的JavaScript方法?

什么是最有用,最实用的方法,扩展内置的JavaScript对象,如string,数组,date,布尔,math等?

  • 格式
  • 修剪
  • 填充
  • replaceAll & replaceAll

排列

  • 指数

date

  • toMidnight

注意:请每个答案发布一个扩展的方法。

string全部replace:

String.prototype.replaceAll = function(search, replace) { //if replace is not sent, return original string otherwise it will //replace search string with 'undefined'. if (replace === undefined) { return this.toString(); } return this.replace(new RegExp('[' + search + ']', 'g'), replace); }; var str = 'ABCADRAE'; alert(str.replaceAll('A','X')); // output : XBCXDRXE 

这是String.replaceAll()方法的另一个实现

 String.prototype.replaceAll = function(search, replace) { if (replace === undefined) { return this.toString(); } return this.split(search).join(replace); } 

这个和这里发布的解决scheme之间的区别在于,这个实现在string中正确处理正则expression式特殊字符以及允许字匹配

 Array.prototype.indexOf = Array.prototype.indexOf || function (item) { for (var i=0; i < this.length; i++) { if(this[i] === item) return i; } return -1; }; 

用法:

 var list = ["my", "array", "contents"]; alert(list.indexOf("contents")); // outputs 2 

的String.format

 String.prototype.format = function (values) { var regex = /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g; var getValue = function (key) { if (values == null || typeof values === 'undefined') return null; var value = values[key]; var type = typeof value; return type === 'string' || type === 'number' ? value : null; }; return this.replace(regex, function (match) { //match will look like {sample-match} //key will be 'sample-match'; var key = match.substr(1, match.length - 2); var value = getValue(key); return value != null ? value : match; }); }; 

用法:

 alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' })); //alerts Program: hello world 

James Padolsey有大量的String.prototype函数

https://github.com/padolsey/string.prototype

这些包括:

  • camelize
  • 包含
  • 计数
  • 提取
  • 的forEach
  • forEachWord
  • linkify
  • 许多
  • 随机
  • 去掉
  • 相反
  • 缩短
  • 分类
  • toDOM
  • 修剪
 // left trim String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); } // right trim String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); } // left and right trim String.prototype.trim = function () { return this.ltrim().rtrim(); } 

string填充:

 String.prototype.padLeft = function (length, character) { return new Array(length - this.length + 1).join(character || ' ') + this; } 'trial'.padLeft(7, 'X'); // output : 'XXtrial' 'trial'.padLeft(7); // output : ' trial' String.prototype.padRight = function (length, character) { return this + new Array(length - this.length + 1).join(character || ' '); } 'trial'.padRight(7, 'X'); // output : 'trialXX' 'trial'.padRight(7); // output : 'trial ' 

PHP.JS是将大部分PHP函数转换为JavaScript的非常好的工作。 他们目前有一个非常可观的名单:

在线: http : //phpjs.org/functions/index

Prototype库中的Function.prototype.bind

callapply类似,但允许您返回对在特定上下文中调用的函数的引用,而不是立即执行。 也允许你咖喱参数。 它成为ECMAScript 5的一部分非常有用,并且已经在浏览器中实现。

 Function.prototype.bind = function() { var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function() { var local_args = args.concat(Array.prototype.slice.call(arguments)); if (this !== window) local_args.push(this); return __method.apply(object, local_args); } } 

各种列表操作原型总是很好。 既然你只希望每个职位都有一个职位,那么我只需要发布通过SML发现的foldl (它“折叠”列表,左到右,当然还有一个反例)。

 Array.prototype.foldl = function(fnc,start) { var a = start; for (var i = 0; i < this.length; i++) { a = fnc(this[i],a); } return a; } 

一些微不足道的例子可能是:

 var l = ["hello" , "world"]; l.foldl(function(i, acc) { return acc+" "+i; }, "") // => returns "hello world" 

可悲的是,标准DOM方法返回true数组的失败使得这些方法中的很多都变得毫无用处。 如果你使用某种types的Lib,他们通常会定义像这样的方法(map,filter,exists等)。

Date.toMidnight

 Date.prototype.toMidnight = function(){ this.setMinutes(0); this.setSeconds(0); this.setHours(0) } 

这是Date对象的一个​​很好的扩展,它允许你很容易地设置date的格式。 它使用PHP的date语法,所以那些熟悉PHP的人会很快得到它。 其他人也有一个在网站上可能的交换机的巨大列表。 就个人而言,我还没有find更简单的方法来格式化date到各种格式。

date格式

我可以在这里find我使用很多的函数集合:

http://svn.asplib.org/asplib1.2/core/string.asp

http://docs.hyperweb.no/objects/String/

我已经使用了Scott Koon概述的Array.Map函数几次。

http://www.lazycoder.com/weblog/2009/08/12/a-simple-map-function-for-plain-javascript-arrays/

 Array.prototype.map = function(fn) { var r = []; var l = this.length; for(i=0;i<l;i++) { r.push(fn(this[i])); } return r; }; 

数组包含:

 Array.prototype.contains = function(obj) { for (var i=0; i < this.length; i++) { if(this[i] === obj) return i; } return -1; } 

用法:

 var arr = [1, 2, 3]; alert(arr.contains(2)); 

这个小帮助函数告诉你数组是否包含一个对象。 如果是,则返回该对象的索引,否则返回-1。

免费星期五下午提示:永远不要修改对象原型。 那只是要求一个痛苦的世界 – 我学会了这个艰难的道路:)

这两个是用于插入和删除数组中的特定位置的元素的包装,因为我不喜欢名称splice

 // insert element at index Array.prototype.insertAt = function(element, index) { this.splice(index, 0, element); } // delete element from index Array.prototype.removeAt = function(index) { this.splice(index, 1); } 

一些更有用的数组方法摆脱使用索引:

 Array.prototype.first = function() { return this[0] || undefined; }; Array.prototype.last = function() { if(this.length > 0) { return this[this.length - 1]; } return undefined; }; Array.prototype.max = function(array){ return Math.max.apply(Math, array); }; Array.prototype.min = function(array){ return Math.min.apply(Math, array); }; 

MooTools库中的一些有用function:

Function.delay

用于在给定的毫秒后执行一个函数。

 // alerts "hello" after 2 seconds. (function() { alert("hello"); }).delay(2000); ​ 

Number.times

与Ruby的times方法类似,它接受一个函数并执行N次,其中N是数字值。

 // logs hello 5 times (5).times(function() { console.log("hello"); }); 

使用这样的原型链:

 String.prototype.AddWorld = function() { return this+'World' } "Hello ".AddWorld(); // returns the string "Hello World" 
 // This replaces all instances of 'from' to 'to' even when // 'from' and 'to' are similar (ie .replaceAll('a', 'a ')) String.prototype.replaceAll = function(from, to) { var k = this; var i = 0; var j = from.length; var l = to.length; while (i <= k.length) if (k.substring(i, i + j) == from) { k = k.substring(0, i) + k.substring(i).replace(from, to); i += l; } else i++; return k; }; 

http://maiaco.com/articles/js/missingArrayFunctions.php上有一篇很好的文章,描述了添加到数组原型的六个有用的函数。; 函数是linearSearch(与另一个答案中给出的indexOf相同),binarySearch,retainAll,removeAll,unique和addAll。 文章还包括六个函数的JavaScript代码和示例代码,展示了如何使用它们。

这是一个大写string的原型函数:

 String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } 

使用类似于underscore.js库或Angular使用lodash库。