简体   繁体   English

在具有多个值的字符串上使用Includes方法

[英]Using the Includes method on a string with multiple values

I want to check if a string has any of the following words, apple, pear, orange and if it does, do some code. 我想检查一个字符串是否包含以下任何单词,苹果,梨,橙色,如果有,请执行一些代码。 However my code only currently checks for the first word, apple and not the other 2. Fruit variable gets sent from a client side. 但是,我的代码目前仅检查第一个单词,apple,而不检查其他两个单词。Fruit变量从客户端发送。

var fruit = fruit;

if (fruit.includes(["apple", "pear", "orange"])
{ 
    //do some code
}

I tried | 我试过 instead of a comma 而不是逗号

I need it so it checks all for all of the words, not just the first 我需要它,所以它检查所有单词,而不仅仅是第一个单词

You could use the some method: 您可以使用some方法:

if (["apple", "pear", "orange"].some(x => fruit.includes(x))) {
    // Do something...

You can use regex instead of includes() with a loop to solve it. 您可以在循环中使用正则表达式而不是includes()来解决它。

Demo: 演示:

 var fruit = "green dpear"; if (/\\b(apple|pear|orange)\\b/.test(fruit)) { console.log('match'); } else { console.log('not_match'); } 

.includes() returns a Boolean (true/false) and it appears that you want the actual matches to return instead. .includes()返回一个布尔值(true / false),并且看来您希望实际返回的匹配项。 .find() returns the match but like .include() it stops after the first match so you'll need to iterate through the search keys. .find()返回匹配项,但就像.include()它在第一个匹配项之后停止,因此您需要遍历搜索键。

The following demo runs .filter() through the array to be searched ( primary ). 下面的演示在要搜索的数组( primary )中运行.filter() )。 .filter() will return the current value that's evaluated as true. .filter()将返回评估为true的当前值。 By running .includes() on the search array ( search ) inside the .filter() you can search each element of array primary . 通过在.filter()内的搜索数组( search .includes()上运行.includes() ,可以搜索数组primary每个元素。

 const primary = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']; const search = ['beta', 'delta', 'omega']; const matches = (array1, array2) => array1.filter(word => array2.includes(word)); console.log(matches(primary, search)); 

you can use forEach loop 您可以使用forEach循环

const fruit = ['apple', 'orange'];

fruit.forEach( function(v, i) {
    if ( fruit[i].includes('orange') ) {
    // do you stuff
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM