简体   繁体   English

检查数组 javascript 中的 substring

[英]Check substring in array javascript

when I have the word SAC and Assessoria inside the array it just returns the first if, what is wrong with this logic?当我在数组中有单词 SAC 和 Assessoria 时,它只返回第一个 if,这个逻辑有什么问题?

If the array (skills) has the substring SAC I want to make a setState with response.data.SAC which is also an array如果数组(技能)具有 substring SAC,我想用 response.data.SAC 创建一个 setState,它也是一个数组

If the array (skills) has the substring Assessoria I want to make a setState with response.data.AC which is also an array如果数组(技能)有 substring Assessoria,我想用 response.data.AC 创建一个 setState,它也是一个数组

if you have both substrings SAC and Assessoria, I want to make a setState with response.data.SAC and response.data.AC, they are both arrays如果你同时有子字符串 SAC 和 Assessoria,我想用 response.data.SAC 和 response.data.AC 创建一个 setState,它们都是 arrays

code below:下面的代码:

getDataTab() {
    const URL = `${Utils.ngrok_service}`;

    const skills = this.props.manager.workerClient.attributes.routing.skills;

    axios.post(URL).then((response) => {

      skills.map((item, index) => {

        if (item.includes('SAC')) {
          console.log('SAC EXISTE');
          this.setState({ options: response.data.SAC });
        } else if (item.includes('Assessoria')) {
          console.log('AC EXISTE');
          this.setState({ options: response.data.AC });
        } else if (item.includes('SAC') && item.includes('Assessoria')) {
          console.log('ambos EXISTE');
          this.setState({
            options: [...response.data.SAC, ...response.data.AC],
          });
        } else {
          console.log('nada EXISTE');
        }
      });
    });
  }

You are setting the state once on each iteration, instead of iterating over the whole array first to check the conditions.您在每次迭代时设置 state 一次,而不是先迭代整个数组以检查条件。 The order of your conditional checks is also incorrect.您的条件检查的顺序也不正确。

let hasSAC = false, hasAssessoria = false;
skills.forEach(item=>{
    hasSAC = hasSAC || item.includes("SAC");
    hasAssessoria = hasAssessoria || item.includes("Assessoria");
});
if(hasSAC && hasAssessoria){
     console.log('ambos EXISTE');
     this.setState({
        options: [...response.data.SAC, ...response.data.AC],
     });
} else if(hasSAC){
     console.log('SAC EXISTE');
     this.setState({ options: response.data.SAC });
} else if(hasAssessoria){
    console.log('AC EXISTE');
    this.setState({ options: response.data.AC });
} else {
    console.log('nada EXISTE');
}

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

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