最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论
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.")
}
发布评论

评论列表(0)

  1. 暂无评论