![](/img/trans.png)
[英]comparing different values of two arrays and returning one filtered array in JavaScript
[英]Comparing two arrays in Javascript for different values
Java语言专家,需要您的帮助。
我需要比较两个不同的数组并检查不同的值。 这些值来自相同形式的多选择元素。 我尝试获取当前值的列表(cacheTermList)并检查更改时的新值(newTermList)。 我的想法是,如果要输入新值,我想将id传递给ajax调用,然后将一些数据返回到屏幕。
码:
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 {
}
});
忍受我,我不太倾向于使用Javascript。 我试图通过在加载时设置cachedTermList来获取当前值列表,然后在选择更改时,将newTermList设置为该字段的新值,然后对其进行循环,并检查该列表中未包含的值缓存列表。
虽然我可以看到情况发生了,并且转储了两个术语列表并看到了不同的值,但是在我的生命中,我无法获得将其推入到缓存列表中的值,以便下次元素更改时,它不会保留一次又一次地将相同的值发送给ajax调用。 .push()执行后,它只添加不带值的',,'。 我要去哪里错了?
这是典型的闭环问题。 所有success
回调都引用相同的i
。 在执行回调时,循环已经完成,并且i
将获得值newTermList.length + 1
,因此newTermList[i]
将返回undefined
。
您必须通过引入新的作用域来捕获索引或值,这可以通过调用函数来完成(JavaScript 没有块作用域)。
更新:另一个问题是$.inArray
不返回布尔值,而是元素的索引或-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);
}
});
}
还请记住,所有Ajax调用基本上都将同时执行。 循环不会等到一个呼叫结束。 如果您想一次执行一次调用,则可以使用jQuery的Deferred
对象 。
您正在for循环中使用ajax
,并将newTermList项目推入其成功处理程序中。 由于默认情况下ajax是异步的,因此循环不会等待ajax请求完成。 尝试将推送代码放在ajax调用之外。 但这在ajax调用失败的情况下将不起作用,可能是您不想在ajax调用失败时将项目添加到缓存中。
试试这个
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.