<分区>
标签 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/