javascript - 如何检查数组中的值是否已存在,如果不存在则将其插入数组

标签 javascript html arrays

在 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/

相关文章:

javascript - 从数组导出常量

javascript - Webpack 输出文件

javascript - JQGrid 减少窗口调整大小事件中的列数

php - 单击提交按钮时从数据库中选择数据

html - 如何让 CSS 选择以字符串开头的 ID(不是在 Javascript 中)?

javascript - 在 React-bootstrap 中单击 Dropdown.Item 后防止关闭

javascript - 如何移动背景图像图案?

java - Android AutoCompleteTextView 如何忽略多余的空格

arrays - Array<MutableCollection> 的 Swift 扩展不允许 reverse()

arrays - 如何在 mongodb 中更新多个数组元素