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

标签 javascript html arrays

我基本上试图循环遍历一个数组来检查一个项目是否已经存在:

If the the item exists, remove it

If the item does not exist, push it to the array

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

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

关于Javascript:将项目推送到数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623921/

相关文章:

c++ - 二进制搜索递减列表?

javascript - 具有重复值检查的多个输入

javascript - 在所有其他内容上导航以及与导航一起响应内容?

C# - 将 HTML 源代码解析为 XML

jquery - 仅向类的元素添加强标记

javascript - PHP javascript 关联数组

Javascript memoize 查找数组

javascript - 无法通过 id 获取 div 元素以在 Internet Explorer 中显示 gif

更新组件后 JavaScript 不起作用

Javascript:通过数组映射后编辑变量