javascript 数组去重兼容性处理的核心在于区分基本类型和引用类型,并针对旧环境(如 ie8)提供 polyfill。对于基本类型,使用 set 或 indexof 即可;对于包含对象、数组的复杂结构,必须通过深度比较或序列化来实现。在低版本浏览器中,需手动实现 array.prototype.includes 或使用 json.stringify 进行简单去重。

如何处理基本类型与引用类型的去重差异
基本类型可以直接比较值,而引用类型即使内容相同也是不同对象。处理这种差异的关键是识别数据类型,对基本类型使用哈希表或 Set,对引用类型使用深度克隆或序列化后的字符串进行比较。

function deepClone(obj, hash = new WeakMap()) {
if (obj === null) return obj;
if (typeof obj !== 'object') return obj;
if (hash.has(obj)) return hash.get(obj);
const clone = Array.isArray(obj) ? [] : {};
hash.set(obj, clone);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key], hash);
}
}
return clone;
}
function uniqueByDeepCompare(arr) {
const result = [];
arr.forEach(item => {
const isDuplicate = result.some(existing => JSON.stringify(existing) === JSON.stringify(item));
if (!isDuplicate) {
result.push(item);
}
});
return result;
}
const input = [{a: 1}, {a: 1}, [1, 2], [1, 2]];
console.log(uniqueByDeepCompare(input)); // [{a: 1}, [1, 2]]如何在低版本浏览器中实现兼容的去重逻辑
在 IE8 等不支持 ES6 的环境中,Set 和 includes 不可用。需要利用 indexOf 检查重复项,或者为 Array.prototype 添加 includes 方法的 Polyfill。对于对象去重,由于 JSON.stringify 会忽略 undefined 和函数,且顺序敏感,需谨慎使用。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

// Polyfill for Array.prototype.includes
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement, fromIndex) {
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) return false;
var n = fromIndex | 0;
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (O[k] === searchElement) {
return true;
}
k++;
}
return false;
};
}
// Compatible unique for basic types
function compatibleUnique(arr) {
return arr.filter(function(item, index) {
return arr.indexOf(item) === index;
});
}
const basicInput = [1, 2, 2, 3, 4, 4];
console.log(compatibleUnique(basicInput)); // [1, 2, 3, 4]基于 JSON.stringify 去重的具体限制是什么
使用 JSON.stringify 进行去重时,如果对象中包含 undefined、函数或 Symbol,这些属性会被忽略,导致不同结构的对象被误判为相同。此外,对象键的顺序变化也会导致序列化结果不同,从而无法去重。

















