只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:

    var value = str.includes("hello", "hi", "howdy");

想象一下逗号表示“或”。

它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。

有什么方法可以做到吗?


当前回答

与数组数据/的精确匹配

const dataArray = ["amoos", "rifat", "hello"]; const findId = (data, id) => { 让res = data。Find (el => el == id) 返回res ?真:假; } console.log(findId(dataArray, 'Hi')) // false console.log(findId(dataArray, 'amoos')) // true

其他回答

你可以这样做

["hello", "hi", "howdy"].includes(str)

这是一个有争议的选择:

String.prototype.includesOneOf = function(arrayOfStrings) {
  if(!Array.isArray(arrayOfStrings)) {
    throw new Error('includesOneOf only accepts an array')
  }
  return arrayOfStrings.some(str => this.includes(str))
}

允许你做以下事情:

'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True

扩展字符串本机原型:

if (!String.prototype.contains) {
    Object.defineProperty(String.prototype, 'contains', {
        value(patterns) {
            if (!Array.isArray(patterns)) {
                return false;
            }

            let value = 0;
            for (let i = 0; i < patterns.length; i++) {
                const pattern = patterns[i];
                value = value + this.includes(pattern);
            }
            return (value === 1);
        }
    });
}

允许你做以下事情:

console.log('Hi, hope you like this option'.toLowerCase().contains(["hello", "hi", "howdy"])); // True

你也可以这样做:

Const STR = "hi, there" Const res = str.includes("hello") || str.includes("hi") || str.includes('howdy'); console.log (res);

只要其中一个include返回真值,value就为真,否则,它就为假。这在ES6中工作得非常好。

另一个!

let result const givenStr = 'A, X' //values separated by comma or space. const allowed = ['A', 'B'] const given = givenStr.split(/[\s,]+/).filter(v => v) console.log('given (array):', given) // given contains none or only allowed values: result = given.reduce((acc, val) => { return acc && allowed.includes(val) }, true) console.log('given contains none or only allowed values:', result) // given contains at least one allowed value: result = given.reduce((acc, val) => { return acc || allowed.includes(val) }, false) console.log('given contains at least one allowed value:', result)