简体   繁体   English

比较JavaScript中两个数组的不同值

[英]Comparing two arrays in Javascript for different values

Javascript gurus, I need your help. Java语言专家,需要您的帮助。

I need to compare two different arrays and check for different values. 我需要比较两个不同的数组并检查不同的值。 The values are coming from the same form multi select element. 这些值来自相同形式的多选择元素。 I tried getting a list of current values (cacheTermList) and checking for new value on change (newTermList). 我尝试获取当前值的列表(cacheTermList)并检查更改时的新值(newTermList)。 The idea is I want to pass an id to an ajax call if a new value was input, and return some data to the screen. 我的想法是,如果要输入新值,我想将id传递给ajax调用,然后将一些数据返回到屏幕。

Code: 码:

var cachedTermList = $('select#edit-categories').val();

      if (cachedTermList == null) {
        var cachedTermList = new Array();
      }

      $('select#edit-categories').chosen().change(function() {
        var newTermList = $('select#edit-categories').val();

        if (cachedTermList != null) {
          for(var i = 0; i < newTermList.length; i++) {
          alert(newTermList[i]);
            if (!($.inArray(newTermList[i], cachedTermList))) {
              $.ajax({
                 type: "GET",
                 url: "/classifieds/js/term/" + newTermList[i],
                 success: function(data){
                   //$('div#term-help-text').html(data);
                   cachedTermList.push(newTermList[i]);
                   alert(cachedTermList);
                 }
               });
            }
          }
        } else {

        }
      });

Bear with me, I don't tend to work with Javascript too often. 忍受我,我不太倾向于使用Javascript。 I was trying to get a current list of values by setting cachedTermList on load, then when the select changes, set a newTermList to the new value of the field, then loop it, and check for a value in that list that is not in the cached list. 我试图通过在加载时设置cachedTermList来获取当前值列表,然后在选择更改时,将newTermList设置为该字段的新值,然后对其进行循环,并检查该列表中未包含的值缓存列表。

While I could see things happen, and dump both term lists and see different values, for the life of me I could not get it to push the found value to the cached list so that the next time the element changes, it doesn't keep sending the same value to the ajax call again and again. 虽然我可以看到情况发生了,并且转储了两个术语列表并看到了不同的值,但是在我的生命中,我无法获得将其推入到缓存列表中的值,以便下次元素更改时,它不会保留一次又一次地将相同的值发送给ajax调用。 After the .push() executes, it just adds ',,,' without values. .push()执行后,它只添加不带值的',,'。 Where am I going wrong? 我要去哪里错了?

It is the typical closure - loop problem. 这是典型的闭环问题。 All success callbacks reference the same i . 所有success回调都引用相同的i At the time the callbacks are executed, the loop already finished and i will have the value newTermList.length + 1 , so newTermList[i] will return undefined . 在执行回调时,循环已经完成,并且i将获得值newTermList.length + 1 ,因此newTermList[i]将返回undefined

You have to capture the index or the value by introducing a new scope, which can be done by calling a function (JavaScript has no block scope). 您必须通过引入新的作用域来捕获索引或值,这可以通过调用函数来完成(JavaScript 没有块作用域)。

Update: Another problem is that $.inArray does not return a boolean value, but the index of the element or -1 . 更新:另一个问题是$.inArray不返回布尔值,而是元素的索引或-1 So you have to compare the return value against -1 . 因此,您必须将返回值与-1比较。

$('select#edit-categories').chosen().change(function() {
    // ...
    for(var i = 0; i < newTermList.length; i++) {
        if ($.inArray(newTermList[i], cachedTermList) === -1) {
            addTerm(newTermList[i], cachedTermList);
        }
    }
    //...
});


function addTerm(term, target) {
    $.ajax({
        type: "GET",
        url: "/classifieds/js/term/" + term,
        success: function(data){
            //$('div#term-help-text').html(data);
            target.push(term);
            alert(target);
        }
    });
}

Also keep in mind that all Ajax calls will basically be executed at the same time. 还请记住,所有Ajax调用基本上都将同时执行。 The loop does not wait until one call finished. 循环不会等到一个呼叫结束。 If you want to execute the calls one at a time, you can use jQuery's Deferred objects . 如果您想一次执行一次调用,则可以使用jQuery的Deferred对象

You are using ajax in a for loop and pushing the newTermList item in its success handler. 您正在for循环中使用ajax ,并将newTermList项目推入其成功处理程序中。 Since ajax is async by default the loop is not going to wait for the ajax request to get completed. 由于默认情况下ajax是异步的,因此循环不会等待ajax请求完成。 Try to put the pushing code outside the ajax call. 尝试将推送代码放在ajax调用之外。 But this will not work if the ajax call fails, may be you dont want to add the item into cache when the ajax call fails. 但这在ajax调用失败的情况下将不起作用,可能是您不想在ajax调用失败时将项目添加到缓存中。

Try something like this 试试这个

for(var i = 0; i < newTermList.length; i++) {
      alert(newTermList[i]);
        if (!($.inArray(newTermList[i], cachedTermList))) {
          $.ajax({
             type: "GET",
             context: i,//Here I am setting the value of i into context which can be used in the success handler using this keyword
             url: "/classifieds/js/term/" + newTermList[i],
             success: function(data){
               //$('div#term-help-text').html(data);
               cachedTermList.push(newTermList[this]);
               alert(cachedTermList);
             }
           });
        }
      }

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

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