比较 array[i].response 到通过函数参数传递的字符串

我有一个包含的数组


const submissions = [{

  question: 'blah blah blah blah',

  response: 'response goes here'

},

我有一个接受提交数组和字符串的函数。我需要检查响应提交 [i].response 对字符串。如果存在则返回 true。


let submissions = [{

  question: 'blah blah blah blah',

  response: 'response goes here'

}];


function checkString(submissions, string) {

  for (let i = 0; i < submissions.length; i++) {

    if (submissions[i].response === string) {

      return true;

    }

  }

  return false;

}


console.log(checkString(submissions,'response goes here'));

如果调用函数 checkString(submissions, 'response goes here') 应该返回 true。这总是返回 false。



慕姐8265434
浏览 97回答 2
2回答

哔哔one

您可以简单地使用一些函数并包含函数,该函数将检查是否array&nbsp;response包含string您正在检查的内容。该includes()方法确定数组是否在其条目中包含某个值,返回true或false适当。let submissions = [{&nbsp; question: 'blah blah blah blah',&nbsp; response: 'response goes here'}];var checkStr = submissions.some(i => i.response.includes('response goes here'));console.log(checkStr)

慕哥9229398

你可以用一些在您的代码片段中,您想检查响应中是否存在字符串您的代码无法正常工作,因为您正在使用===所以我的编辑是使用includesECMAScript 6 或更高版本:booleanResult&nbsp;=&nbsp;submissions.some(e&nbsp;=>&nbsp;e.response.includes(string))ECMAScript 5:booleanResult&nbsp;=&nbsp;submissions.some(function&nbsp;(e)&nbsp;{&nbsp; &nbsp;return&nbsp;e.response.includes(string); });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript