我有一个网络应用程序可以跟踪您的购买并显示不同的统计数据。在其中一个页面中,我有 jQuery ajax 请求,这些请求通过 API 调用加载用户的购买。然后所有购买都作为 JavaScript 对象放入一个名为 G_PURCHASES
的全局数组中。
到目前为止一切顺利。然后我调用一个函数,该函数使用 jQuery 的 Deferred()
使其可链接;它迭代 G_PURCHASES
并通过检查 G_PURCHASES[i] 获取所有不同的
通过使用 purchase.item.category
(查看购买对象的相关结构)。 item.categoryArray.includes()
包含在另一个名为 G_CATEGORIES
的全局数组中。如果不是,则将其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 包括对引用相等性的检查,因此可能有两个具有相同属性和值的对象,但它们仍然是不同的对象,因此它们的引用不相等。您可能想要手动检查每个类别对象的类别 ID 和名称以查找重复项。
关于JavaScript 函数 Array.prototype.includes() 在 for 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46620838/