javascript - 如何在 Lodash 中将 _.pull() 与正则表达式一起使用?
问题描述
我想在匹配某个正则表达式时从数组中删除元素。
我想要一个类似的结果。
const array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(array, 'b', 'c',);
console.log(array); // [ 'a', 'a', ]
只是,我想使用正则表达式而不是字符串。但这并没有达到那个结果。
const array = ['a', 'b', 'c', 'a', 'b', 'c'];
const re = /(b|c)/gm
_.pull(array, re,);
console.log(array); // ["a", "b", "c", "a", "b", "c"]
我究竟做错了什么?
解决方案
该_.pull()
方法不接受谓词,请使用_.remove()
:
从数组中删除谓词返回真值的所有元素
const array = ['a', 'b', 'c', 'a', 'b', 'c'];
const re = /b|c/
_.remove(array, c => re.test(c));
console.log(array); // ["a", "a"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
推荐阅读
- ruby-on-rails - ActiveModel:: Accounts::RetreatsController#create 中缺少属性错误
- netlogo - rnd:weighted-one-of-list work 不会返回我认为应该的分布
- r - 循环和条件的问题。在值应该有效时将其标记为无效
- jquery - jQuery .find('li').length 必须来自兄弟/孩子?
- java - 尝试构建 Rest 服务时 Spring Boot 失败
- r - 根据第二个数据帧 R 上的索引替换数据帧中的值
- vba - 如何将记录信息从 ListBox 存储到 Table?
- java - 一旦我在函数之外,优先队列中的值就会被删除,为什么?
- android - 如何使用 popBackStack() 返回到我的 Android 应用程序中的上一个片段?
- python - 密码包含特殊字符时“拒绝用户访问”