javascript - 因为一道题对JS中RegExp中test()方法的返回值产生疑惑。
迷茫
迷茫 2017-04-10 15:23:18
0
3
319

是这样的,最近在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);返回了匹配的结果,为什么会这样?还是我理解错了?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回覆 (3)
PHPzhong

可能你没有理解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)

      大家讲道理

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

        最新下載
        更多>
        網站特效
        網站源碼
        網站素材
        前端模板
        關於我們 免責聲明 Sitemap
        PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!