这有效:
var animals = ["caterpillar", "dog", "bird"];
var catMatch = /cat/i;
var catFound = animals.some(function(animalName) {
return catMatch.test(animalName);
});
console.log(catFound);

但这不是
var animals = ["caterpillar", "dog", "bird"];
var catMatch = /cat/i;
var catFound = animals.some(catMatch.test);
console.log(catFound);

为什么第二个版本不起作用?
答案 0 :(得分:2)
RegExp.prototype.test
取决于其this
值。您可以将所需的this
值传递给some
:
var catFound = animals.some(catMatch.test, catMatch);