![](/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.