简体   繁体   English

如何防止添加到Javascript数组的元素被覆盖?

[英]How to prevent elements being added to a Javascript array from being overridden?

I currently have addToClients() that adds a new element to the clients array when the button is being pressed. 我目前有addToClients() ,当按下按钮时,它将向clients数组添加一个新元素。 I want to add the new value to clients whenever the button is pressed, and have the value maintain in the array even after we input a new element(so I can use the autocomplete feature of jQuery). 我想每当按下按钮时就将新值添加到clients ,并且即使在我们输入新元素之后也要在数组中保留该值(因此我可以使用jQuery的autocomplete功能)。
However, now whenever I press submit again, the previous element being added is being overridden by the new element, so I can't keep it in the array (FYI clients array is in a separate js file from this html file that contains these code). 但是,现在每当我再次按Submit时,添加的前一个元素就会被新元素覆盖,因此我无法将其保留在数组中(FYI clients数组与包含这些代码的html文件位于单独的js文件中)。 Is there any problem in my implementation? 我的执行过程中有什么问题吗?
Here is what the html page looks like: html页面如下所示: 在此处输入图片说明

function addToClients(){
            if (!($("#client-name").val() in clients)){
                clients.push($("#client-name").val())
            }
        }

The HTML code related to this part is here: 与这部分有关的HTML代码在这里:

<input type = "text"
                 id = "client-name"
                 onkeypress="auto()" 
                 placeholder="Client">
         <input type = "text" id = "reams" placeholder="#reams">
         <button id="btn"> Submit</button> 

Here is the array in a separate js file linked to the HTML 这是链接到HTML的单独js文件中的数组

 clients = [
          "Shake Shack",
          "Toast",
          "Starbucks",
    ];

Maybe this will do: 也许这样做:

if (jQuery.inArray( $("#client-name").val(), clients ) == -1){
     clients.push($("#client-name").val())
 }

You can use includes which will check value have exist in array then return true or false ... 您可以使用includes来检查数组中是否存在值,然后返回true或false ...

 var arr = [1,4,7]; var added = 4; if(!arr.includes(added)) { arr.push(added); } console.log(arr); 

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

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