开发者

Call a function if a string contains any items in an array

How can I call a JavaScript functio开发者_StackOverflow社区n if a string contains any of the items in an array?

Yes, I can use jQuery :)


You could use the grep function to find if there are any elements that satisfy the condition:

// get all elements that satisfy the condition
var elements = $.grep(someArray, function(el, index) {
    // This assumes that you have an array of strings
    // Test if someString contains the current element of the array
    return someString.indexOf(el) > -1;
});

if (elements.length > 0) {
    callSomeFunction();
}


You could use some(), a Mozilla extension which has been added to ECMAScript 5:

var haystack = 'I like eggs!';
if(['spam', 'eggs'].some(function(needle) {
    return haystack.indexOf(needle) >= 0;
})) alert('spam or eggs');


Simply loop over the items in the array and look for the value. That's what you have to do anyway even if you use some method to do it for you. By looping yourself you can easily break out of the loop as soon as you find a match, that will by average cut the number of items you need to check in half.

for (var i=0; i<theArray.length; i++) {
  if (theArray[i] == theString) {
    theFunction();
    break;
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜