开发者问题收集

Javascript 循环遍历数组:无法读取未定义的属性“slice”

2020-07-06
72

我的 api 响应如下所示:

id: (...)
user_id: (...)
symptoms: "Sore throat, Headache"

id: (...)
user_id: (...)
symptoms: "Anorexia  (Loss of appetite), Shortness of breath (Difficult in breathing), Myalgias (Muscle pains), Sore throat, Headache"

我尝试将用户的 症状 与现有症状类别进行匹配。用户最多可以有 14 种症状。当我拆分和切片数组以获取单个症状并进行匹配时,我不断收到 无法读取未定义的属性“切片” 错误。

当我尝试为对象设置默认值时,如果用户的症状少于 14 种,错误仍然存​​在。

我的代码:

getSymNum (symp, c) {
        var counter = 0

      for (var xc in c) {

        var symp1 = c[xc].symptoms.split(',')[0]
        var symp2 = c[xc].symptoms.split(',')[1].slice(1)
        var symp3 = c[xc].symptoms.split(',')[2].slice(2)
        var symp4 = c[xc].symptoms.split(',')[3].slice(3)
        var symp5 = c[xc].symptoms.split(',')[4].slice(4)
        var symp6 = c[xc].symptoms.split(',')[5].slice(5)

        if (symp3 !== undefined){       
        console.log("hello ha")
        
        }

        if (symp1 === symp) {
        counter++
        } else if (symp2 === symp) {
          counter++
        } else if (symp3 === symp)  {
          counter++
        } else if (symp4 === symp) {
          counter++
        } else if (symp5 === symp) {
          counter++
        } else if (symp6 === symp) {
          counter++
        }

      }
      return counter  
      
    },
1个回答

您可以使用数组/字符串方法(如 contains()indexOf() )来优化检查:

etSymNum (symp, c) {
  var counter = 0

  for (var xc in c) {
    if(c[xc].symptoms.indexOf(symp) !== -1){
      counter++;
    }
  }
  return counter  
},
Greedo
2020-07-06