简体   繁体   English

使用纯 javascript 从数组中删除值

[英]Removing a value from array with pure javascript

I realize this may have been asked before in different ways, but I have yet to find an answer that is suitable for this particular situation as it needs to be written in plain JS (no jQuery).我意识到这可能以前以不同的方式被问过,但我还没有找到适合这种特殊情况的答案,因为它需要用纯 JS(没有 jQuery)编写。 This is a class assignment so there's nothing I can do about that.这是课堂作业,所以我无能为力。

Basically I was asked to make a list of checkboxes that when clicked send their associated value to an array, then when clicked again to uncheck the box it should remove said value.基本上,我被要求制作一个复选框列表,单击时将其关联值发送到数组,然后再次单击以取消选中该框时,它应该删除所述值。

The html for this is这个 html 是

            <div>
              <fieldset class="checks">
                <legend><span>What are your favorite JavaScript libraries/frameworks?</span></legend>
                <input type="checkbox" id="jq" value="jQuery" name="libraries" />
                <label for="jq" id="jqLabel">jQuery</label>
                <input type="checkbox" id="angular" value="AngularJS" name="libraries" />
                <label for="angular" id="angularLabel">AngularJS</label>
                <input type="checkbox" id="node" value="NodeJS" name="libraries" />
                <label for="node" id="nodeLabel">NodeJS</label>
                <input type="checkbox" id="react" value="ReactJS" name="libraries" />
                <label for="react" id="reactLabel">ReactJS</label>
                <input type="checkbox" id="backbone" value="Backbone" name="libraries" />
                <label for="backbone" id="backboneLabel">Backbone</label>
            </fieldset>
            </div>

            <p id="testPara"></p>

and the corresponding javascript I have so far is到目前为止,我拥有的相应 javascript 是

// Function for JS library selections
var libraryArray = [];

function libraryQuery(event) {

   if (event === undefined) { // get caller element in IE8
      event = window.event;
   }

   var callerElement = event.target || event.srcElement;
   var libraryName = callerElement.value;
   if (callerElement.checked) {
     libraryArray.push(libraryName);
     document.getElementById("testPara").innerHTML = libraryArray;
   }
   else {
     var listItems = document.querySelectorAll(".checks input");

     for (var i = 0; i < libraryArray.length; i++) {
        if (listItems[i].value === libraryName) {
         // remove element at index i from array
           libraryArray.splice(i, 1);
           document.getElementById("testPara").innerHTML = libraryArray;

        }
     }
   }
}

function createEventListeners() {
  var libraries = document.getElementsByName("libraries");
  if (libraries[0].addEventListener) {
     for (var i = 0; i < libraries.length; i++) {
        libraries[i].addEventListener("change", libraryQuery, false);
     }
  } else if (libraries[0].attachEvent) {
     for (var i = 0; i < libraries.length; i++) {
        libraries[i].attachEvent("onchange", libraryQuery);
     }
  }

}

if (window.addEventListener) {
   window.addEventListener("load", createEventListeners, false);
} else if (window.attachEvent) {
   window.attachEvent("onload", createEventListeners);
}

This format is basically the same as what was used in my textbook for another assignment, which works there, but for some reason is giving me really funky results on this project.这种格式与我的教科书中用于另一项作业的格式基本相同,在那里工作,但由于某种原因,在这个项目上给了我非常时髦的结果。

For one it will add to the array no problem, but sometimes it will add multiple copies of the same value after checking, unchecking, then checking again, which is no good.对于一个它会添加到数组中没有问题,但有时它会在检查,取消检查,然后再次检查后添加相同值的多个副本,这是不好的。

As for the removal when unchecking boxes, sometimes it works, sometimes it doesn't.至于取消选中复选框时的删除,有时有效,有时无效。 Sometimes it removes a totally different value than the one associated with the current checkbox being unchecked.有时,它会删除与当前未选中的复选框关联的值完全不同的值。

I believe the problem to be somewhere in this for loop, and more specifically it may be a problem with the if statement within it.我相信问题出在这个 for 循环中的某个地方,更具体地说,它可能是其中的 if 语句有问题。 But after a ton of tinkering I am just stumped on how to correct the issue (I could also be totally wrong in that the error is somewhere else).但是经过大量的修补后,我只是对如何纠正问题感到困惑(我也可能完全错了,因为错误在其他地方)。

 for (var i = 0; i < libraryArray.length; i++) {
    if (listItems[i].value === libraryName) {
     // remove element at index i from array
       libraryArray.splice(i, 1);
       document.getElementById("testPara").innerHTML = libraryArray;

    }
 }

Any help is truly appreciated.任何帮助都非常感谢。 Here is a jsfiddle .这是一个jsfiddle

You've complicated this, all you need to do is check if the box is checked, and the value isn't already in the array, then push it to the array, otherwise just remove it based on the index.你已经把这个复杂化了,你需要做的就是检查这个框是否被选中,并且该值不在数组中,然后将它推送到数组中,否则只需根据索引将其删除。

function libraryQuery() {
    var libraryName = this.value,
        index       = libraryArray.indexOf(libraryName);

    if (this.checked &&  index === -1 ) {
        libraryArray.push(libraryName);
    } else {
        libraryArray.splice(index, 1);
    }
    document.getElementById("testPara").innerHTML = libraryArray;
}

FIDDLE小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM