开发者

is there any way to make my jquery search better?

开发者 https://www.devze.com 2023-01-15 16:18 出处:网络
var myarr= Array(\'test1\',\'test2\',\'test3\'); var searchTerm = \"test\"; var rS开发者_高级运维earchTerm = new RegExp( searchTerm,\'i\');

var myarr= Array('test1','test2','test3');

var searchTerm = "test";
var rS开发者_高级运维earchTerm = new RegExp( searchTerm,'i');

$.each(myarr, function(i) {
        if (myarr[i].match(rSearchTerm)) {
            //item found
        }

    });​

guys is there any way to make my search algorithm better ? "myarr" will be a big array so i want to make sure that i'm using the best way to search in it

thanks alot


I would recommend the following (since jQuery provides this convenience):

$.each(myarr, function(index, value) {
    if (rSearchTerm.test(value)) {
        // item found
    }
});

The only other approach to make this faster is probably to do this without jQuery in a plain for-loop, since it does not involve callbacks:

for (var i = 0; i < myarr.length; i++) {
    if (rSearchTerm.test(myarr[i])) {
        // item found
    }
}

EDIT: I changed .match() to .test(), like Andy E suggested.

0

精彩评论

暂无评论...
验证码 换一张
取 消