You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript filter方法过滤排除含黑名单子串的URL数组?

用Array.filter()简洁实现URL黑名单过滤

嘿,想要用更简洁的方式替代for循环完成这个URL过滤需求?Array.filter()搭配Array.some()就能完美解决,代码清爽又易读!

核心思路

我们需要保留不包含黑名单中任何子串的URL:

  • 用filter()遍历所有URL,只留下符合条件的项
  • 用some()检查当前URL是否匹配黑名单里的任意子串,再通过!取反,筛选出完全不匹配的URL

完整实现代码

const urls = [ 
  'http://example.com/people/chuck', 
  'http://example.com/goats/sam', 
  'http://example.com/goats/billy', 
  'http://example.com/goats/linda', 
  'http://example.com/cows/mary', 
  'http://example.com/cows/betty', 
  'http://example.com/people/betty'
];
const blacklist = ['cows', 'goats'];

// 简洁的filter实现
const cleanUrls = urls.filter(url => !blacklist.some(item => url.includes(item)));

结果说明

执行后cleanUrls会得到以下结果:

[
  'http://example.com/people/chuck',
  'http://example.com/people/betty'
]

简单解释下两个方法的作用:

  • filter():遍历数组,返回所有使回调函数返回true的元素组成的新数组
  • some():只要数组中有一个元素使回调函数返回true,整体就返回true;这里我们取反,意思是“黑名单里没有任何一个子串出现在当前URL中”

内容的提问来源于stack exchange,提问作者Ivan Town

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:57:15