2010-01-23 61 views

回答

1

你可以使用some(),已添加对ECMAScript 5一个Mozilla扩展:

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

您可以使用grep功能查找是否有满足条件的所有元素:

// 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(); 
} 
1

只需遍历数组中的项目,寻找价值。即使你使用某种方法为你做这些,你也必须这样做。通过循环自己,只要你找到一场比赛,你就可以轻松地跳出循环,这将平均减少你需要检查的项目的数量。

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

不要使用'for..in'来遍历数组! – Christoph 2010-01-23 11:36:57

+0

@Christoph:感谢您的高举。我通常不会使用for..in,并且它在教程中使用时没有任何可能的风险。 – Guffa 2010-01-23 12:08:27

+0

周围有很多糟糕的JS代码;这就是流行语言的问题:每个人都声称“知道”他们,并且倾向于传播他们的知识;即使是来自'官方'来源的信息,你认为这些人应该知道他们在谈论的内容有时只是错误的(*咳嗽* Apple JavaScript Coding Guidelines) – Christoph 2010-01-23 12:32:46

相关问题