是这样的,最近在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); 返回了匹配的结果,为什么会这样?还是我理解错了?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
filter 方法 (Array) (JavaScript)
应该是你没有看清楚题目,function(val){return reg.test(val);},这段函数的的结果是传递给seq.filter()这个方法作为参数的,也就是seq.filter()的参数最后是true或者false,而filter()函数的结果最后才赋值给res对象