簡體   English   中英

Javascript:將項目推送到數組不起作用

[英]Javascript: Pushing items to an Array doesn't work

我基本上是試圖遍歷一個數組,以檢查是否已經存在一個項目:

如果該項目存在, 請將刪除

如果該項不存在,則將其推入數組

但是,我的代碼僅允許我添加一項 它忽略了我嘗試添加的所有其他值。

var inclfls = []; //new empty array
function addfile(val) {
 if (inclfls.length != 0) {
        for (var i = 0; i < inclfls.length; i++) {
            if (inclfls[i] == val) {
                a.style.background = "#999";
                inclfls.splice(i, 1); //remove it
            }
            else {
                a.style.background = "#2ECC71";
                inclfls.push(val); //push it
            }
        }
    }
    else {
        a.style.background = "#2ECC71";
        inclfls.push(val);
    }

    alert(inclfls.length);
}

我究竟做錯了什么?

使用數組方法,它要簡單得多:

function addfile(val) {
  var index=inclfls.indexOf(val);
  if(index===-1){ 
   inclfls.push(val); 
   a.style.background = "#999";
  }else{ 
    inclfls.splice(index,1);
    a.style.background = "#2ECC71";
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM