[英]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.