【问题标题】:how to tell if an array includes any of the substrings如何判断数组是否包含任何子字符串
【发布时间】:2020-06-11 04:28:33
【问题描述】:

我有一个带有 javascript 字符串的数组,看起来像这样:

let array = ['cat', 'dog', 'bird']

我的字符串中有一些单词由| 分隔 这是字符串:

let string = 'pig|cat|monkey' 

那么我如何知道我的数组是否在我的字符串中至少包含这些项目之一?

【问题讨论】:

  • 请分享您的尝试。您可以在"|" 字符上拆分字符串,然后使用array.somearray.includes 来检查“至少一个”条件。

标签: javascript arrays ecmascript-6


【解决方案1】:

您可以使用数组方法.some()检查字符串中是否存在数组中的动物

const animals = ['cat', 'dog', 'bird']
const string = 'pig|cat|monkey'
const splitString = string.split('|')


const hasAnimals = animals.some(animal => splitString.includes(animal))

您可以使用数组方法.reduce()获取存在的动物

const presentAnimals = splitString.reduce((acc, animal) => {
  const animalExists = animals.includes(animal)
  if (animalExists) {
    acc.push(animal)
  }
  return acc
}, [])

或者,如果您更喜欢单衬里

const presentAnimals = splitString.reduce((acc, animal) => animals.includes(animal) ? [...acc, animal] : [...acc], [])

【讨论】:

    【解决方案2】:

    split 字符串由|trim 组成。 使用数组includes 来检查some 字。

    const has = (arr, str) =>
      str.split("|").some((word) => arr.includes(word.trim()));
    
    let array = ["cat", "dog", "bird"];
    let string = "pig|cat|monkey";
    
    console.log(has(array, string));
    console.log(has(array, "rabbit|pig"));

    【讨论】:

      【解决方案3】:

      使用字符| 拆分字符串,然后运行forEach 循环并检查数组中是否存在parts 的值。

      let array = ['cat', 'dog', 'bird', 'monkey'];
      let str = 'pig|cat|monkey';
      //split the string at the | character
      let parts = str.split("|");
      //empty variable to hold matching values
      let targets = {};
      //run a foreach loop and get the value in each iteration of the parts
      parts.forEach(function(value, index) {
        //check to see if the array includes the value in each iteration through
        if(array.includes(value)) {
          targets[index] = value; //<-- save the matching values in a new array    
          //Do something with value...
        }
      })
      console.log(targets);
      I have an array with javascript strings that looks something like this: let array = ['cat', 'dog', 'bird'] and I have some words inside my string that are separated by a | this is the string: let string = 'pig|cat|monkey' so how do I know if my array
      includes at least one of these items within my string?

      【讨论】:

        【解决方案4】:

        尝试以下方法:-

        let array = ['cat', 'dog', 'bird'];
        
        let string = 'ca';
        
        var el = array.find(a =>a.includes(string));
        
        console.log(el);

        【讨论】:

          猜你喜欢
          • 2020-08-26
          • 1970-01-01
          • 2017-10-15
          • 2012-11-11
          • 2012-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多