题目:
- 如传入的数组元素为
[123, "meili", "123", "mogu", 123]
,则输出:[123, "meili", "123", "mogu"]
- 如传入的数组元素为
[123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"]
,则输出:[123, [1, 2, 3], [1, "2", 3], "meili"]
- 如传入的数组元素为
[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"]
,则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]
function dis(arr) {
const resObj = {};
const res = [];
arr.forEach((item) => {
const key = item + JSON.stringify(item); //定义唯一的key
if (!resObj[key]) { //检测resObj中是否存在唯一的key
res.push(item); //把唯一的key放在数组中
resObj[key] = item; //唯一的数值存在变量中缓存起来
}
})
console.log(resObj)
return res;
}
const test1 = [123, "meili", "123", "mogu", 123,"mogu"];
const test2 = [123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"];
const test3 = [123, { a: 1 }, { a: { b: 1 } }, { a: "1" }, { a: { b: 1 } }, "meili"];
console.log(dis(test1)); //[123, "meili", "123", "mogu"]
console.log(dis(test2)); //[123, [1, 2, 3], [1, "2", 3], "meili"]
console.log(dis(test3)); //[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]