简体   繁体   English

我似乎无法清空javascript数组

[英]I can't seem to empty a javascript array

I know there are a lot of these questions on Stackoverflow but none of them work for me. 我知道在Stackoverflow上有很多这样的问题,但是它们对我都不起作用。 I would like to post my own code and try and find out what I am doing wrong. 我想发布自己的代码并尝试找出我在做什么错。

So, I have a function that adds a bunch of items to an array. 因此,我有一个将一堆项目添加到数组的函数。 The page is never refreshed, as is the way it is designed. 页面永远不会像设计方式那样刷新。 So when that same function is called again the array MUST be emptied because: 因此,当再次调用同一函数时,必须清空该数组,因为:

  1. Items added to an array are linked to a specific item on the page that the user selected. 添加到数组的项目链接到用户选择的页面上的特定项目。
  2. When a new item is selected the old item's things should not be shown in the array. 选择新项目时,旧项目的内容不应显示在数组中。 Only the new item's things. 只有新项目的东西。
  3. The array is populated from checkbox values and that array is then used to create different checkboxes on a popup modal form. 从复选框值填充该数组,然后使用该数组在弹出模式窗体上创建不同的复选框。

Here is the code to populate the array: 这是填充数组的代码:

// Here I tried emptying the array with below mentioned methods. The array is defined outside of the function. I have also tried defining it inside.
    var count = 0;
  var optionsSelected = 0;
  $('input[name="extrasSelected"]:checked').each(function() {
      var selected = $(this).val().split("|");
      extras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
      optionsSelected++;
      count++;
  });

  $('input[name="extrasSelected"]:not(:checked)').each(function() {
    var notSelected = $(this).val().split("|");
      extras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
      count++;
  });

  extras.sort();

This entire thing is working perfectly. 整个过程运行良好。 Except when I select a new item. 除了我选择一个新项目时。 The popup displays and checkboxes are created with the previous item's things as well as checkboxes with the new item's things. 弹出显示和复选框使用上一项的内容创建,复选框也使用新项目的内容创建。

I have tried to use: 我尝试使用:

extras = [];
extras.pop();
extras.length = 0
while (extras > 0) {
    extras.pop();
}

Actually, I have tried all methods seen on stackoverflow and google. 实际上,我已经尝试了在stackoverflow和google上看到的所有方法。 So I am guessing that I am doing something wrong. 所以我想我做错了什么。

Any help would be greatly appreciated! 任何帮助将不胜感激!

EDIT 编辑

Additional Code As Requested: 根据要求的附加代码:

var extras = [];
$("#doLookup").click(function() {  
  var count = 0;
  var optionsSelected = 0;
  $('input[name="extrasSelected"]:checked').each(function() {
      var selected = $(this).val().split("|");
      extras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
      //alert(extras[0][1]);
      optionsSelected++;
      count++;
  });

  $('input[name="extrasSelected"]:not(:checked)').each(function() {
    var notSelected = $(this).val().split("|");
      extras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
      //alert(extras[0][1]);
      count++;
  });

  extras.sort();

   if (extras.length > 0) {
                    optionalsJSHead = '<table width="100%"><tr><th style="width: 40%;"><b>Optional Extra</b></th><th style="text-align:right;width:15%"><b>Retail</b></th><th style="text-align:right;width:15%"><b>Trade</b></th><th style="text-align:right;width:15%"><b>Market</b></th><th style="text-align:right"><b>Include</b></th></tr>';
                    optionalsJSBody = '';
                    if (parseInt(year) === parseInt(guideYear)) {
                      for (i = 0; i < extras.length; ++i) {
                          optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'" disabled="disabled"/></td></tr>';
                      }
                    } else {
                      for (i = 0; i < extras.length; ++i) {
                        if (extras[i][4] == 'notChecked') {
                          optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'"/></td></tr>';
                        } else {
                          optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'" checked /></td></tr>';
                        }
                      }
                    }
                    optionalFooter = '</table>';
                    optionalsJS = optionalsJSHead + optionalsJSBody + optionalFooter;
                  }
});

From my understanding, you can create a temporary array, populate it with new values and then assign it to extras variable. 据我了解,您可以创建一个临时数组,使用新值填充它,然后将其分配给extras变量。 See the code below: 请参见下面的代码:

 var extras = []; // actual array whose items you want to use $("#doLookup").click(function() { var tmpExtras = []; // temporary array to get the new items you want. var count = 0; var optionsSelected = 0; $('input[name="extrasSelected"]:checked').each(function() { var selected = $(this).val().split("|"); tmpExtras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked']; //alert(extras[0][1]); optionsSelected++; count++; }); $('input[name="extrasSelected"]:not(:checked)').each(function() { var notSelected = $(this).val().split("|"); tmpExtras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked']; //alert(extras[0][1]); count++; }); tmpExtras.sort(); // now assign tmpExtras to extras array, so that // you can get the new items extras = tmpExtras; // ... rest of code that uses extras 

If you should set array as empty before adding some value to the array. 如果应在将一些值添加到数组之前将array设置为空。 I think you should set it in both places before you try to fill it: extras[count] = []; extras[count] = .... 我认为您在尝试填充它之前,应该在两个地方都设置它: extras[count] = []; extras[count] = .... extras[count] = []; extras[count] = .... . extras[count] = []; extras[count] = .... And why do you need the array of array? 而为什么需要数组数组呢? maybe you should used just array and every time rewrite it? 也许您应该只使用数组,并且每次都重写它? like: 喜欢:

extras = [selected[0], selected[1], selected[2], selected[3], 'checked'];

then no needs to set array like empty before filling. 那么在填充之前无需将数组设置为空。

Your click event is bound to a single item. 您的点击事件绑定到单个项目。 #doLookup is an id selector which means that there is a single item with the id="doLookup" in the document. #doLookup是一个ID选择器,这意味着在文档中只有一个ID为“ doLookup”的项目。

How do you intend to let the function know that the array needs to be emptied? 您打算如何让函数知道需要清空数组?

A simple fix would be to bind the click event to another selector such as .doLookupClass etc and then check inside the function when a different item was selected and empty the array. 一个简单的解决方法是将click事件绑定到另一个选择器(例如.doLookupClass等),然后在函数内部检查何时选择了其他项目并清空数组。

It would seem I made a rookie mistake. 看来我是个菜鸟错误。 The array was being emptied. 阵列已清空。 However since I am creating textboxes with javascript I forgot to empty the div before adding the new ones, causing the old ones to still display. 但是,由于我使用JavaScript创建文本框,因此我忘记了在添加新文本框之前清空div,导致旧文本框仍然显示。 And I didn't post that part of the code so that is why you guys probably couldn't assist. 而且我没有发布代码的那部分,所以这就是你们可能无法协助的原因。

I changed 我变了

$("#myDiv").append(OptionalsJS);

to

$("#myDiv").empty().append(OptionalsJS);

What a stupid mistake... X_X anyway, thanks for the assistance anyway! 真是个愚蠢的错误...还是X_X,感谢您的帮助!

Maybe the whole thing can be done in a much easier fashion? 也许可以轻松得多地完成整个过程?

See here for a working example 请参阅此处的工作示例

 var extras = []; // actual array $("#doLookup").click(function() { extras = []; // temporary array $('input[name="extrasSelected"]').each(function() { with ($(this)){ var cb=val().split("|"); var state=(is(':checked')?'':'un')+'checked'; } extras.push([cb[0], cb[1], cb[2], cb[3], state]); }); $('#show').html(JSON.stringify(extras)); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type=checkbox value="a|b|c|d" name="extrasSelected" /><br/> <input type=checkbox value="e|f|g|h" name="extrasSelected" /><br/> <input type=checkbox value="i|j|k|l" name="extrasSelected" /><br/> <input type=checkbox value="m|n|o|p" name="extrasSelected" /><br/> <input type=checkbox value="q|r|s|t" name="extrasSelected" /><br/> <input type=checkbox value="u|v|w|x" name="extrasSelected" /><br/> <input type="button" id="doLookup" value="go"/> <div id="show" /> 

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

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