我想通过添加一个新的方法来扩展Javascript内置的Array对象。 searchByRegexp
基本上,这个方法会得到一个regexp作为输入,然后返回: 如果没有一个元素符合正则表达式,则返回一个空字符串。
快速和肮脏的 (...抚玩):
Array.prototype.searchByRegexp = function (rx) {
for(var i = 0, ln = this.length; i < ln; i++) {
// test item i
if(rx.test(this[i])) {
return this[i] + "";
}
}
// return an empty string if no matches are found
return "";
}
然而,你可能希望实施 更多 一般 方法 而不是....
Array.prototype.find = function(delegate) {
for(var i = 0, ln = this.length; i < ln; i++) {
if(delegate(this[i])){
return this[i];
}
}
return null;
}
Array.prototype.findAll = function(delegate) {
var results = [];
for(var i = 0, ln = this.length; i < ln; i++) {
if(delegate(this[i])){
results.push(this[i]);
}
}
return results ;
}
Array.prototype.each = function (delegate) {
for (var i = 0, ln = this.length; i < ln; i++) {
delegate(this[i], i);
}
}
...然后可以像这样执行regex比较。
// test values
var sizes = ["Small", "Medium", "Large", "Extra-Large", "Extra-Extra-Large"];
// Print single value or blank
document.write(sizes.find(function(size){
return /large/i.test(size);
}) || "");
// horizontal rule to separate our results
document.write("<hr/>");
// Print all matches
sizes.findAll(function(size){
return /large/i.test(size);
}).each(function(size){
document.write(size + "<br/>");
});
目前,使用Google Chrome浏览器,所提供的解决方案打破了对数组的迭代。 As of today, using Google Chrome, the provided solution breaks the iteration over the array.
在 Array.prototype.searchByRegexp = function ...
如果你用 for (var k in arrayInstance)
价值 searchByRegexp
将在键中,而不仅仅是真正的数组键。
为了防止这种情况,你应该使用 Object.defineProperty(Array.prototype, ...
Object.defineProperty(Array.prototype, 'searchByRegexp', {
value: function (rx) {
for(var i = 0, ln = this.length; i < ln; i++) {
// test item i
if(rx.test(this[i])) {
return this[i] + "";
}
}
// return an empty string if no matches are found
return "";
},
enumerable: false
});