我有一羣人,並希望根據某些條件進行過濾,在這種情況下,我想搜索一個「男性」,但應該只返回一個結果,但使用此設置I因爲正則表達式也捕獲女性,所以一切都恢復了。使用RegExp從JavaScript數組返回完全匹配
我試過匹配「\ bmale」或「/ \ bmale」,但沒有得到任何回報。我知道我需要使用一個字邊界,但由於某種原因,它不能解決問題。
var people = [["Adelaide", 2, "yes", "female"],
["Ada", 2, "yes", "female"],
["Amanda", 1, "yes", "female"],
["Wolf", 3, "no", "male"],
["Rhonda", 1, "no", "female"]];
var isMale = function(x) {
var myMatch = new RegExp("male");
var test = String(x).match(myMatch);
return String(x).match(myMatch);
}
var filteredArray=people.filter(isMale);
document.writeln(filteredArray);
只是再次提醒我:爲什麼你使用正則表達式呢? –
這可以做得更簡單:'var filteredArray = people.filter(function(itm){return itm [2] ==「male」;});' – Alxandr
@Alxandr:'return itm [3]' –