我基本上试图循环遍历一个数组来检查一个项目是否已经存在:
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/