解析url参数 深拷贝代码
function getParam(url) {
if (typeof url !== 'string') {
return null;
}
let index = url.indexOf('?');
if (index < 0) {
return {};
}
const params = url.substring(index + 1).split('&');
const obj = {};
for (let i = 0; i < params.length; i++) {
const param = params[i];
const paramParts = param.split('=');
// 验证参数格式是否正确
if (paramParts.length !== 2) {
return `${param} 的参数不合法`;
}
const key = decodeURIComponent(paramParts[0]);
const value = decodeURIComponent(paramParts[1]);
// 检查是否已存在相同的参数名,如果是数组则添加到数组中,否则创建数组保存多个值
if (obj.hasOwnProperty(key)) {
if (Array.isArray(obj[key])) {
obj[key].push(value);
} else {
obj[key] = [obj[key], value];
}
} else {
obj[key] = value;
}
}
return obj;
}
console.log(getParam(url1), 'getParam(url1)');
const copyObj = (obj) => {
let newobj = null;
//判断是否需要继续进行递归
if (typeof (obj) == 'object' && obj !== null) {
newobj = obj instanceof Array ? [] : {};
for (var i in obj) {
newobj[i] = copyObj(obj[i])
} //如果不是对象直接赋值
} else {
newobj = obj
}
return newobj;
}