javascript - 如果值是'在'排列

时间:2016-05-10 20:58:46

标签: javascript arrays

我正在尝试循环出一个名称列表和console.logging匹配的值。我使用错误(如果数组中的)?

    for (var i = 0; i < this.state.apiResponse.length ; i++) {

      var selectedChars = this.state.chosenChars
      var returnedChars = this.state.apiResponse[i].name

      console.log(selectedChars)
      console.log(returnedChars)


      // I think i'm making a mistake with this if statement
      if (returnedChars in selectedChars) {
        console.log(this.state.apiResponse[i].name);            
      }

selectedChars数组和返回值:

["Luke Skywalker", "Han Solo"]

Luke Skywalker
Han Solo
Chewbacca

3 个答案:

答案 0 :(得分:1)

您必须使用string.indexOf(substring)

if (selectedChars.indexOf(returnedChars) !== -1) {
  console.log(this.state.apiResponse[i].name);            
}

string.indexOf(substring)返回字符串中子字符串的索引,如果找不到子字符串,则返回-1。如果我们检查“除-1之外的任何内容”,我们可以确保returnedChars中的selectedChars

答案 1 :(得分:0)

不要使用in运营商。而是使用indexOf

for (var i = 0; i < this.state.apiResponse.length ; i++) {

  var selectedChars = this.state.chosenChars
  var returnedChars = this.state.apiResponse[i].name

  console.log(selectedChars)
  console.log(returnedChars)


  // I think i'm making a mistake with this if statement
  if (selectedChars.indexOf(returnedChars)!==-1) {
    console.log(this.state.apiResponse[i].name);            
  }

答案 2 :(得分:0)

是的,它不是python,它是javascript:)

您可以在数组上使用indexOf()方法。

  if (selectedChars.indexOf(returnedChars) > -1) {
    console.log(this.state.apiResponse[i].name);            
  }

抱歉,search()是字符串。