[英]JavaScript function Array.prototype.includes() doesn't work in for loop
我有一個網絡應用程序,可以跟蹤您的購買並顯示不同的統計信 在其中一個頁面中,我有jQuery ajax請求從API調用加載用戶的購買。 然后,所有購買都被放入一個名為G_PURCHASES
的全局數組中作為JavaScript對象。
到現在為止還挺好。 然后我調用一個使用jQuery的Deferred()
函數使其可鏈接; 它通過使用Array.includes()
通過檢查G_PURCHASES[i].item.category
是否包含在另一個名為G_CATEGORIES
的全局數組中)來迭代G_PURCHASES
並獲取所有不同的purchase.item.category
(看一下購買對象的相關結構)。 Array.includes()
。 如果不是那么push()
它push()
入G_CATEGORIES
。
我遇到的一個問題是,即使將category
對象推入G_CATEGORIES
數組后,每次都會返回Array.includes()
檢查返回false
。 檢查相關代碼和輸出以清除它。
// Relevant structure of the purchase object
purchase = {
item: {
category: {
categoryID: int,
name: string
}
}
// Relevant code
var G_PURCHASES = []; // array declared globally
// it is successfully filled with @purchase objects from another function
var G_CATEGORIES = []; // array declared globally
// to be filled by @LoadAllCategories
var LoadAllCategories = function() {
// make a jQuery Deffered
let func = $.Deferred(function() {
let allP = G_PURCHASES; // make a shortcut
let allC = C_CATEGORIES; // make another shortcut
for (var i = 0; i < allP.length; i++) {
// get whether the current purchase.item.category
// already exists in allC array
let exist = allC.includes(allP[i].item.category);
// console.log the above result
console.log('i = ' + i + ', category exists = ' + exist);
// if it doesn't exist then push it in
if (!exist) allC.push(allP[i].item.category);
}
this.resolve();
});
return func;
}
// Input
G_PURCHASES has 6 @purchase objects with 3 unique item.category 'ies
// Output
i = 0, category exists = false
i = 1, category exists = false
i = 2, category exists = false
i = 3, category exists = false
i = 4, category exists = false
i = 5, category exists = false
// Result
G_CATEGORIES contains duplicate categories
我試圖使用Array.indexOf()
和jQuery的$.inArray()
沒有成功。 無論我是什么console.log()
我似乎無法找到錯誤所在。 所以,如果你能告訴我為什么Array.includes()
在這個for
循環中不起作用我會找到你,我會給你買啤酒!
Well包括對引用相等性的檢查,因此可能有兩個具有相同屬性和值的對象,但它們仍然是不同的對象,因此它們的引用不相等。 您可能希望手動檢查每個類別對象的categoryID和名稱以查找重復項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.