简体   繁体   English

无法清空JS数组

[英]Can't empty JS array

Yes, I am having issues with this very basic (or so it seems) thing. 是的,我对此非常基本(或似乎如此)的东西有疑问。 I am pretty new to JS and still trying to get my head around it, but I am pretty familiar with PHP and have never experienced anything like this. 我对JS还是很陌生,但仍然想尽一切办法,但是我对PHP非常熟悉,并且从未经历过类似的事情。 I just can not empty this damn array, and stuff keeps getting added to the end every time i run this. 我只是不能清空这个该死的数组,每次我运行这个东西时,东西总是不断增加。

I have no idea why, and i am starting to think that it is somehow related to the way chekbox id's are named, but i may be mistaking.... 我不知道为什么,而且我开始认为它与chekbox ID的命名方式有关,但我可能会误会....

id="alias[1321-213]" , id="alias[1128-397]" , id="alias[77-5467]" and so on. id="alias[1321-213]"id="alias[1128-397]"id="alias[77-5467]"等。

I have tried sticking 我试过粘

checkboxes = []; and checkboxes.length = 0; checkboxes.length = 0;

In every place possible. 在所有可能的地方。 Right after the beginning of the function, at the end of the function, even outside, right before the function, but it does not help, and the only way to empty this array is to reload the page. 在函数开始之后,在函数结尾处,甚至在函数末尾,恰好在函数之前,但这无济于事,清空此数组的唯一方法是重新加载页面。 Please tell me what I am doing wrong, or at least point me to a place where i can RTFM. 请告诉我我做错了什么,或者至少将我指向可以进行RTFM的地方。 I am completely out of ideas here. 我在这里完全没有主意。

function() {

    var checkboxes = new Array();
    checkboxes = $(':input[name="checkbox"]');

        $.each(checkboxes,
            function(key, value) {
                     console.log(value.id);                            
                     alert(value.id);
          }
        );
     checkboxes.length = 0;                          
}

I have also read Mastering Javascript Arrays 3 times to make sure I am not doing something wrong, but still can't figure it out.... 我也已经阅读了3次Mastering Javascript Arrays ,以确保我没有做错什么,但是仍然无法弄清楚。

I think there's a lot of confusion coming out of this because you are clearing the array -- just maybe not for the purpose you want, or at the wrong time, etc. 我认为这会引起很多混乱,因为正在清理阵列 -可能不是出于您想要的目的,或者在错误的时间等。

 function () { var checkboxes = new Array(); // local-scope variable checkboxes = $(':input[name="checkbox"]'); // new instance $.each(checkboxes, /* ... */); // (truncated for brevity) checkboxes.length = 0; // this clears the array // but, for what...? // nothing happens now } 

As per your snippet, every call to the function recreates and clears the array. 按照您的代码片段,每次调用该函数都会重新创建并清除该数组。 However, all work with the array is done while the array is full (nothing happens after it's cleared). 但是,阵列的所有工作都是在阵列已满时完成的(清除后什么也没有发生)。

Also, checkboxes is a private variable to the function. 同样, checkboxes是该函数的私有变量。 The variable only exists during execution of the function and is forgotten once the function is done. 该变量仅在函数执行期间存在,并且在函数完成后会被忘记。

So, what is the big picture? 那么,总体情况如何? Why are you trying to clear the array? 为什么要清除阵列?


To take a guess, it sounds like you're intending on clearing it for the next call of the function. 猜测一下,听起来您打算在下次调用该函数时清除它。
ie (filling in doSomething for function name): 即(为函数名填写doSomething ):

doSomething(); // log all array elements and clears the array
doSomething(); // does nothing, since the array is already empty

To accomplish this, you need to define checkboxes in a single location outside of the function, either as a global variable or using closures ( the heavily more recommended, albeit more complex, option ): 为此,您需要在函数外部的单个位置中定义checkboxes ,既可以将其定义为全局变量,也可以使用闭包( 尽管建议使用更复杂的选项,但建议使用闭包):

NOTE : If you haven't dealt with closures before, they may not make much sense after only a single example. 注意 :如果您以前没有处理过闭包,那么仅举一个例子就可能没有太大意义。 But, there are thousands of resources available , including Stack Overflow , to help explain them better than I can here. 但是,有成千上万的可用资源 ,包括Stack Overflow ,可以比我在这里提供更好的解释。

// closure (or instantly-called function)
// allows for defining private variables, since they are only known by
// code blocks within this function

(function () {
    // private (closure-scoped) variable(s)
    var checkboxes = $(':input[name="checkbox"]');

    function doSomething() {
        $.each(checkboxes, /* ... */);

        checkboxes.length = 0;
    }
})();

The closure will run once, defining checkboxes as the array of inputs while doSomething will iterate the array before clearing it. 闭包将运行一次,将checkboxes定义为输入数组,而doSomething将在清除数组之前对其进行迭代。

Now, the last step is to expose doSomething -- cause, as with checkboxes , it is also private. 现在,最后一步是公开 doSomething原因,与checkboxes ,它也是私有的。 You can accomplish exposing it by passing the function reference from the closure to a variable outside the closure: 您可以通过将函数引用从闭包传递到闭包外部的变量来完成公开:

 var doSomething = (function () {
     /* ... */

     return doSomething;  // note that you DO NOT want parenthesis here
 })();

Is setting length even possible? 是否可以设定长度? ;) ;)

Any way checkboxes is a jquery object not an array. 复选框无论如何都是一个jquery对象而不是一个数组。

When You do checkboxes = $(':input[name="checkbox"]'); 当您做checkboxes = $(':input[name="checkbox"]'); it's not an array any more and whatever there was before has no influence. 它不再是数组,以前的任何东西都没有影响。 It doesn't matter what was in a variable if You assign something new to it in any language I know. 如果用我知道的任何语言为变量分配新内容,则变量中的内容无关紧要。

You are making some jquery related error. 您正在犯一些与jQuery有关的错误。 Please elaborate more so that I can help 请详细说明,以便我能提供帮助

Are You sure You put name="checkbox" in all of them? 您确定将所有名称都放在name =“ checkbox”吗? It doesn't seem to have a lot of sense. 似乎没有太多意义。 Maybe You waned $(':input[ type ="checkbox"]'); 也许您需要$(':input[ type ="checkbox"]'); ?

Edit: that's funny. 编辑:这很有趣。 the above selector isn't too good as well. 上面的选择器也不是很好。 It should be: 它应该是:

$('input:checkbox'); 

as for removing stuff: 至于去除东西:

delete varname 删除变量名

delete arrname[elem] 删除 arrname [elem]

is the right way to do it. 是正确的方法。

assigning null does not change the length but just makes trouble. 分配null不会更改长度,只会带来麻烦。

怎么办呢:

checkboxes = new Array();

您也可以删除它。

delete checkboxes;

When you rerun the function it will search for all checkboxes again. 当您重新运行该功能时,它将再次搜索所有复选框。

Consider this strategy: 考虑以下策略:

function() {
  var checkboxes = $(':input[name=checkbox]:not(.examined)');
  checkboxes.addClass('examined');

  $.each(checkboxes, function(key, value) {
      // ... stuff
  });
}

You could also use .data() if you don't want to "pollute" the DOM. 如果不想“污染” DOM,也可以使用.data()

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

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