简体   繁体   English

如何检查数组中的值是否已经存在以及是否不将其推送到数组中

[英]how to check if a value in array is already exists & if not push it in array

while working around in Js, I need to check if a value in array is present or not & if it exists show error to user, & if not push it in array. 在Js中解决时,我需要检查数组中的值是否存在以及是否存在向用户显示错误,以及是否不将其推送到数组中。 here is my code snippet. 这是我的代码段。

<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();
   }

Simple use this check: 简单使用此检查:

!!~array.indexOf(element)

It returns true if element is in array, returns false if element is absent. 如果element在数组中,则返回true;如果没有element,则返回false。

You can also extend Array type with your own method (ie contains), to use it in your code, like this: 您还可以使用自己的方法(即包含)扩展Array类型,以在代码中使用它,如下所示:

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

Please add your local storage code and fillStcok function for complete functionality. 请添加您的本地存储代码和fillStcok函数以获取完整功能。 The following snippet is for checking duplicate 以下代码段用于检查重复项

  var fruits = ["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 (fruits.indexOf(newItem.value) !== -1) { document.getElementById("errorMsg").innerHTML = "ALREADY IN STOCK!"; document.getElementById("errorMsg").style.display = "block"; } else { document.getElementById("errorMsg").style.display = "none"; fruits.push(newItem.value); } } 
 <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> 

You can always use Array.prototype.find() method, with small extend. 您始终可以使用Array.prototype.find()方法,并进行少量扩展。 It's fast and synchronious. 快速而同步。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/find

var findFunc = function(searchVal, element, index, arr) {
  return searchVal == element
}

var freshOne = fruits.find(findFunc.bind(undefined, newItem.value)) == undefined;

if (freshOne) {
    fruits.push(newItem.value)
} else {
    console.log('Already there');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM