我们如何比较两个多维数组以获得打字稿中的相等性?
我的数组看起来像[{"tagRuleId":3,"organisationId":454654,"tag":"third","type":1,"rule":"lirr","applicableSurveyCount":13},"tagRuleId":1,"organisationId":454654,"tag":"jj","type":1,"rule":"lllllll","applicableSurveyCount":12}]
我创建了一个辅助函数,只有在长度发生变化时才有效。如果订单发生变化或价值发生变化,它将无法运作。到目前为止,我的代码是。
isEqual(value, other) {
// Get the value type
var type = Object.prototype.toString.call(value);
// If the two objects are not the same type, return false
if (type !== Object.prototype.toString.call(other)) return false;
// If items are not an object or array, return false
if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false;
// Compare the length of the length of the two items
var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
if (valueLen !== otherLen) return false;
// Compare two items
var compare = function (item1, item2) {
// Get the object type
var itemType = Object.prototype.toString.call(item1);
// If an object or array, compare recursively
if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
if (!this.isEqual(item1, item2)) return false;
}
// Otherwise, do a simple comparison
else {
// If the two items are not the same type, return false
if (itemType !== Object.prototype.toString.call(item2)) return false;
// Else if it's a function, convert to a string and compare
// Otherwise, just compare
if (itemType === '[object Function]') {
if (item1.toString() !== item2.toString()) return false;
} else {
if (item1 !== item2) return false;
}
}
};
// Compare properties
if (type === '[object Array]') {
for (var i = 0; i < valueLen; i++) {
if (compare(value[i], other[i]) === false) return false;
}
} else {
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (compare(value[key], other[key]) === false) return false;
}
}
}
// If nothing failed, return true
return true;
}
&#13;
此代码有什么问题,或者有更好的方法在角度
中执行此操作答案 0 :(得分:0)
比较数组的最简单方法是将它们转换为JSON并比较字符串:
isEqual(value, other) {
return JSON.stringify(value) == JSON.stringify(other);
}