根据正则表达式匹配选择数组中的对象 [英] Select Objects in Array Based on Regex Match

查看:91
本文介绍了根据正则表达式匹配选择数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用javascript仅返回满足特定条件的数组中的对象?

How can I return only the objects in an array that meet a certain criteria using javascript?

例如,如果我有['apple','avocado','banana','cherry'],并且只想输出以字母'A'开头的水果.

For instance, if I have ['apple','avocado','banana','cherry'] and want to only output fruit that begin with the letter 'A'.

使用下面的Sean Kinsey函数,并尝试通过传递匹配的数组和字母使其更灵活:

Took Sean Kinsey's function below and tried to make it more flexible by passing in the array and letter to match:

函数filterABC(arr,abc){

function filterABC(arr,abc) {

var arr = arr;

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

return filtered.join(); 

}

尝试使用filterABC(arr,'A')或filterABC(arr,'A | B | C |')进行调用,以将所有匹配项从A输出到C,但是这部分有麻烦.

Trying to call it with filterABC(arr,'A') or filterABC(arr,'A|B|C|') to output all matches from A to C but having trouble with this part.

推荐答案

如果定位到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());

这篇关于根据正则表达式匹配选择数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆