JavaScript Array

编程入门 行业动态 更新时间:2024-10-22 10:46:51
JavaScript Array - 过滤掉与特定字符串不匹配的值(JavaScript Array - Filter out values that do not match specific strings)

我试图循环一个数组并过滤掉所有与特定值匹配的项目。

例如,我有这个数组:

const emails = ["nick@hotmail.com", "nick@yahoo.com", "nick@gmail.com", "bob@yahhoo.com", "bob@gmail.com", "boc@test.com"];

我想过滤掉以“结尾”的电子邮件

*@hotmail.com *@gmail.com


我已经给它一个去了,但这不起作用:

const filtered = emails.filter((email) => { return !email.includes('@hotmail.com') || !email.includes('@gmail.com'); });

上例中的首选输出是:

["nick@yahoo.com", "bob@yahhoo.com", "boc@test.com"]

I am trying to loop through an array and filter out all the items that do not match specific values.

For example I have this array:

const emails = ["nick@hotmail.com", "nick@yahoo.com", "nick@gmail.com", "bob@yahhoo.com", "bob@gmail.com", "boc@test.com"];

I would like to filter out emails that end in"

*@hotmail.com *@gmail.com


I have given it a go and got this but this doesn't work:

const filtered = emails.filter((email) => { return !email.includes('@hotmail.com') || !email.includes('@gmail.com'); });

The preferred output from the example above would be:

["nick@yahoo.com", "bob@yahhoo.com", "boc@test.com"]

最满意答案

替换或|| 用和&&

如果您选择所有不包含Hotmail或不包含Gmail的电子邮件,您将获得所有不包含两者的电子邮件,这不是您的目标。 你想得到所有那些不包含hotmail和gmail的东西!

const filtered = emails.filter((email) => { return !email.includes('@hotmail.com') && !email.includes('@gmail.com'); });

Replace the or || with an and &&

If you select all emails which do not contain hotmail OR do not contain gmail, you'll get all of them which don't contain both which isn't your objective. You want to get all of those that do not contain both hotmail and gmail instead!

const filtered = emails.filter((email) => { return !email.includes('@hotmail.com') && !email.includes('@gmail.com'); });

更多推荐

本文发布于:2023-07-05 06:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034390.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JavaScript   Array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!