Javascript:将项目推送到数组并不起作用

时间:2015-11-10 06:05:45

标签: javascript html arrays

我基本上试图遍历数组以检查项目是否已存在:

  

如果该项目存在,删除

     

如果该项目不存在,推送到数组

但是我的代码只允许我添加一个项目。它忽略了我试图添加的所有其他价值。

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

我做错了什么?

1 个答案:

答案 0 :(得分:4)

使用数组方法,它更简单:

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";
 }
}