且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据正则表达式匹配选择数组中的对象

更新时间:2023-02-21 13:23:49

如果定位到ES3(最常见且安全使用的javascript版本),则使用

If targeting ES3 (the version of javascript that is most common, and safe to use) then use

var arr  = ['apple','avocado','banana','cherry'];

var filtered = (function(){
    var filtered = [], i = arr.length;
    while (i--) {
        if (/^A/.test(arr[i])) {
            filtered.push(arr[i]);
        }
    }
    return filtered;
})();
alert(filtered.join());

但是如果您以ES5为目标,则可以使用

But if you are targeting ES5 then you can do it using

var filtered = arr.filter(function(item){
    return /^A/.test(item);
});
alert(filtered.join());

如果需要,您可以通过使用

If you want to you can include the ES5 filter method in ES3 by using

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun /*, thisp*/){
        var len = this.length >>> 0;
        if (typeof fun != "function") 
            throw new TypeError();

        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, this)) 
                    res.push(val);
            }
        }

        return res;
    };
}

请参见 https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter#Compatibility 了解更多信息.

更新 回答更新的问题

var filtered = (function(pattern){
    var filtered = [], i = arr.length, re = new RegExp('^' + pattern);
    while (i--) {
        if (re.test(arr[i])) {
            filtered.push(arr[i]);
        }
    }
    return filtered;
})('A'); // A is the pattern

alert(filtered.join());