【问题标题】:Using RegExp.test for the callback of Array.some [duplicate]使用 RegExp.test 回调 Array.some [重复]
【发布时间】:2018-04-18 23:40:12
【问题描述】:

这行得通:

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

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

【问题讨论】:

    标签: javascript regex callback built-in


    【解决方案1】:

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

    var catFound = animals.some(catMatch.test<b>, catMatch</b>);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      相关资源
      最近更新 更多