在 Js 中工作时,我需要检查数组中的值是否存在,如果存在则向用户显示错误,如果不将其推送到数组中。 这是我的代码片段。
<html>
<body>
<label>Enter an New item to add in Stock</label>
<br> </br>
<input type="text" name=" itemName" id="addItemInStock">
<br></br>
<p id="errorMsg"></p>
<button onclick="addToStock()">Add</button>
<p id="showList"></p>
<select id="showInDropDown">
<option disabled selected style="display: block;">Stock Items</option>
</select>
<script>
var fruitsfromLS = localStorage.getItem("fruits");
var fruits = fruitsfromLS ? JSON.parse(fruitsfromLS) : ["Banana", "Orange", "Apple", "Mango"];
//document.getElementById("showList").innerHTML = fruits;
var newItem = document.getElementById("addItemInStock");
function addToStock() {
if ((newItem.value) === "") {
document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
document.getElementById("errorMsg").style.display = "block";
} else if ((newItem.value) === fruits[i].value)) {
document.getElementById("errorMsg").innerHTML = "aLREADY IN sTOCK!";
document.getElementById("errorMsg").style.display = "block";
} else {
document.getElementById("errorMsg").style.display = "none";
fruits.push(newItem.value);
localStorage.setItem("fruits", JSON.stringify(fruits));
clearAndShow();
}
fillSelect();
}
最佳答案
简单地使用此检查:
!!~array.indexOf(element)
如果元素在数组中,则返回 true,如果元素不存在,则返回 false。
您还可以使用自己的方法(即 contains)扩展数组类型,以在代码中使用它,如下所示:
Array.prototype.contains = Array.prototype.contains || function(element) {
return !!~this.indexOf(element);
};
let a = [ -2, -1, 0, 1, 2, 3, 4, 5 ]; // an example of array
console.log( a.contains(-1) ); // true
console.log( a.contains(10) ); // false
关于javascript - 如何检查数组中的值是否已存在,如果不存在则将其插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504133/