首页 > 因为一道题对JS中RegExp中test()方法的返回值产生疑惑。

因为一道题对JS中RegExp中test()方法的返回值产生疑惑。

是这样的,最近在codewars.com刷题,遇到了这样一道字符串匹配问题:

Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings.
The method takes two parameters, the query string and the array of strings to search, and returns an array.
If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".
Example: If the string to search for is "me", and the array to search is ["home", "milk", "Mercury", "fish"], the method should return ["home", "Mercury"].

一份答案中是这样写的。:

function wordSearch(query, seq){
  var reg = new RegExp(query,"i");
  var res = seq.filter(function(val){
    return reg.test(val);
  });
  return (res.length > 0) ? res : ["Empty"];
}

可是让我不能理解的是,不是说test()返回的是true or false 吗,但是通过结果来看貌似return reg.test(val); 返回了匹配的结果,为什么会这样?还是我理解错了?


应该是你没有看清楚题目,function(val){return reg.test(val);},这段函数的的结果是传递给seq.filter()这个方法作为参数的,也就是seq.filter()的参数最后是true或者false,而filter()函数的结果最后才赋值给res对象


可能你没有理解array 的 filter 方法。filter 第一个参数为一个function,如果这个function的返回值为 true,就把当前值加入到新数组中。关于filter的解释请看这里。https://msdn.microsoft.com/library/ff679973(v=vs.94).aspx

filter 方法将遍历整个数组。当然也可以用下面方式实现:

function wordSearch(query, seq){
    var reg = new RegExp(query,"i");
    var res = [];

    for (var i = 0; i < seq.length; i++) {
        if (reg.test(seq[i])) {
            res.push(seq[i]);
        }
    }

    return (res.length > 0) ? res : ["Empty"];
}

filter 方法 (Array) (JavaScript)

【热门文章】
【热门文章】