【发布时间】:2010-11-11 08:48:51
【问题描述】:
在扩展内置 JavaScript 对象(如字符串、数组、日期、布尔值、数学等)时,您最有用、最实用的方法是什么?
字符串
数组
日期
注意:请为每个答案发布一种扩展方法。
【问题讨论】:
标签: javascript
在扩展内置 JavaScript 对象(如字符串、数组、日期、布尔值、数学等)时,您最有用、最实用的方法是什么?
字符串
数组
日期
注意:请为每个答案发布一种扩展方法。
【问题讨论】:
标签: javascript
字符串全部替换:
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
【讨论】:
'foobar'.replaceAll('foo')。我认为最好明确表示接受正则表达式作为第一个参数。
这是String.replaceAll()方法的另一个实现
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
此解决方案与 here 发布的解决方案之间的区别在于,此实现正确处理字符串中的正则表达式特殊字符并允许单词匹配
【讨论】:
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
【讨论】:
James Padolsey 有大量的 String.prototype 函数
https://github.com/padolsey/string.prototype
这些包括:
【讨论】:
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
【讨论】:
// 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.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 的一个非常好的尝试。他们目前有一个非常令人印象深刻的名单:
【讨论】:
Function.prototype.bind 来自 Prototype 库。
类似于call 和apply,但允许您返回对在特定上下文中调用的函数的引用,而不是立即执行它。还允许您对参数进行柯里化。它非常有用,以至于它成为 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);
}
}
【讨论】:
各种列表操作原型总是很棒。由于每个帖子只需要一个,我将只发布 foldl,这是我通过 SML 发现的(它“折叠”列表,从左到右,它在 foldr 当然有对应部分)。
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 方法无法返回真正的数组,这使得这些方法中的很多都变得毫无用处。如果您使用某种 Lib,它们通常已经定义了类似的方法(map、filter、exists 等)。
【讨论】:
Date.toMidnight
Date.prototype.toMidnight = function(){
this.setMinutes(0);
this.setSeconds(0);
this.setHours(0)
}
【讨论】:
这是 Date 对象的一个很好的扩展,它允许您非常轻松地格式化日期。它使用 PHP 的日期语法,因此熟悉 PHP 的人很快就会掌握它。其他人在网站上也有大量可能的开关列表。就个人而言,我还没有找到更简单的方法将日期格式化为各种格式。
【讨论】:
【讨论】:
我曾多次使用 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 库中的一些有用函数:
用于在给定的毫秒数过去后执行函数。
// alerts "hello" after 2 seconds.
(function() {
alert("hello");
}).delay(2000);
类似于 Ruby 的数字时间方法,它接受一个函数并执行 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"
【讨论】:
String.prototype.appendWord=function(word){ this = this +" "+ word;}"Hello".appendWord("World");
// This replaces all instances of 'from' to 'to' even when
// 'from' and 'to' are similar (i.e .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;
};
【讨论】:
"abaababa".replace(/a/g, "c") => "cbccbcbc"
http://maiaco.com/articles/js/missingArrayFunctions.php 上有一篇不错的文章,描述了添加到 Array 原型的六个有用函数。这些函数是 linearSearch(与另一个答案中给出的 indexOf 相同)、binarySearch、retainAll、removeAll、unique 和 addAll。本文还包括六个函数中每个函数的 JavaScript 代码以及展示如何使用它们的示例代码。
【讨论】:
这是一个字符串大写的原型函数:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
【讨论】:
使用 underscore.js 库之类的东西,或者对于 Angular 使用 lodash 库。
【讨论】: