[英]How to prevent elements being added to a Javascript array from being overridden?
我目前有addToClients()
,當按下按鈕時,它將向clients
數組添加一個新元素。 我想每當按下按鈕時就將新值添加到clients
,並且即使在我們輸入新元素之后也要在數組中保留該值(因此我可以使用jQuery的autocomplete
功能)。
但是,現在每當我再次按Submit時,添加的前一個元素就會被新元素覆蓋,因此我無法將其保留在數組中(FYI clients
數組與包含這些代碼的html文件位於單獨的js文件中)。 我的執行過程中有什么問題嗎?
html頁面如下所示:
function addToClients(){
if (!($("#client-name").val() in clients)){
clients.push($("#client-name").val())
}
}
與這部分有關的HTML代碼在這里:
<input type = "text"
id = "client-name"
onkeypress="auto()"
placeholder="Client">
<input type = "text" id = "reams" placeholder="#reams">
<button id="btn"> Submit</button>
這是鏈接到HTML的單獨js文件中的數組
clients = [
"Shake Shack",
"Toast",
"Starbucks",
];
也許這樣做:
if (jQuery.inArray( $("#client-name").val(), clients ) == -1){
clients.push($("#client-name").val())
}
您可以使用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.