使用RegExp.test进行Array.some的回调

时间:2018-04-18 23:40:13

标签: javascript regex callback built-in

这有效:



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);




为什么第二个版本不起作用?

1 个答案:

答案 0 :(得分:2)

RegExp.prototype.test取决于其this值。您可以将所需的this值传递给some

var catFound = animals.some(catMatch.test, catMatch);