js手撕
判断循环引用
function detectCircularReference(obj) {
const seen = new WeakSet();
function detect(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
if (seen.has(value)) {
return true;
}
seen.add(value);
return Object.values(value).some(detect);
}
return detect(obj);
}
const objA = {};
const objB = { a: objA };
objA.b = objB;
console.log(detectCircularReference(objA));
解析URL参数
function parseUrl(url) {
const queryString = url.split("?")[1];
if (!queryString) return {};
const keyPairs = queryString.split("&");
return keyPairs.reduce((params, item) => {
const [k, v] = item.split("=");
if (params[k] === undefined) {
params[k] = v;
} else if (Array.isArray(params[k])) {
params[k].push(v);
} else {
params[k] = [params[k], v];
}
return params;
}, {});
}
深拷贝
function deepClone(obj, map = new WeakMap()) {
if (obj === null) return null;
if (typeof obj !== "object") return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (obj instanceof Map)
return new Map(
[...obj].map(([key, val]) => [deepClone(key, map), deepClone(val, map)])
);
if (obj instanceof Set)
return new Set([...obj].map((val) => deepClone(val, map)));
if (map.has(obj)) return map.get(obj);
const newObj = new obj.constructor();
map.set(obj, newObj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = deepClone(obj[key], map);
}
}
return newObj;
}