javascript - How to check if an array doesn't contain a string and use it as condition - Stack Overflow

var name = document.getElementById("namebox").value;if (array.includes(name) == false) {alert

var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

Share Improve this question edited Jun 9, 2017 at 8:33 Nate asked Jun 9, 2017 at 4:33 NateNate 1611 gold badge2 silver badges12 bronze badges 15
  • what browser did that not work in? – Jaromanda X Commented Jun 9, 2017 at 4:35
  • This question is already answered here – Parag Jadhav Commented Jun 9, 2017 at 4:35
  • Can you show your Array and working snippet – prasanth Commented Jun 9, 2017 at 4:35
  • codepen.io's default engine – Nate Commented Jun 9, 2017 at 4:35
  • codepen.io's default engine what is this a response to? .... again, what browser did that not work in – Jaromanda X Commented Jun 9, 2017 at 4:38
 |  Show 10 more ments

2 Answers 2

Reset to default 4

because your array is like

[ "name1,score1", "name2,score2"]

searching for "name1" using includes wont work

you'll want something like

if (!array.some(item => item.split(',')[0] === name)) {
    alert(name + " is not in record.")
}

or in pre ES2015

if (!array.some(function (item) {
    return item.split(',')[0] === name;
})) {
    alert(name + " is not in record.");
}

or if your browser doesn't have Array.prototype.some

if (array.filter(function (item) {
    return item.split(',')[0] === name;
}).length === 0) {
    alert(name + " is not in record.");
}

You may try

if (array.indexOf(name) == -1) {
   alert(name + " is not in record.")
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745206902a4616635.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信