javascript - 当值已经存在于使用javascript的数组中时如何显示警告消息

标签 javascript html css

<分区>

如何在使用 javascript 的值已存在于数组中时显示警告消息

var names = [];

var nameInput = document.getElementById("txt1");
var messageBox = document.getElementById("display");

function insert() {
  names.push(nameInput.value);
  clearAndPush();
}

function clearAndPush() {
  nameInput.value = "";
  messageBox.innerHTML = "";
  messageBox.innerHTML += "Names:" + names.join(", ");

  function removeDups(names) {
    let unique = {};
    names.forEach(function(i) {
      if (!unique[i]) {
        unique[i] = true;
      }
    });
    return Object.keys(unique);
  }
  document.getElementById("display").innerHTML = removeDups(names);
}
<label>Name:</label><input type="text" id="txt1" placeholder="Enter Name">
<input type="button" value="Click" onclick="insert()">

<div id="display"></div>

最佳答案

你的问题有点不清楚,但(请随时纠正我)我相信你想检查一个值是否已经在数组中。这非常简单 - 使用 Array.prototype.includes() :

if (names.includes(nameInput.value) {
    alert("The name " + nameInput.value + " is already in the names array.");
}

关于javascript - 当值已经存在于使用javascript的数组中时如何显示警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737822/

上一篇:javascript - d3 中的条形位置与轴不匹配

下一篇:css - 需要有关 CSS 网格设计的建议

相关文章:

javascript - 命名函数表达式

javascript - 两级滤波器或/与

javascript - 停止 iframe youtube 视频

css - 如何更改 javafx 中特定 TreeView 的折叠和展开图标?

javascript - 不显眼的 JQuery 无法在 IE8 中运行?

Javascriptexecutor 可以检测到吗?

iphone - TFHppleElement(Hpple),在iphone上解析HTML

javascript - 如何在用户每次返回主页时停止播放背景视频?

css - 如何在 LESS CSS 1.4+ 中覆盖 mixins

javascript - 在 IE 和 FireFox 中播放 Flash 的 XSLT 问题