参数转编码;递归;转化参数格式
2019-08-23 本文已影响0人
家有饿犬和聋猫
过滤参数,过滤空字符串;
export function paramFilter(params = {}) {
let result = {};
for(let k in params) {
if (params[k] !== undefined && params[k] !== null) {
result[k] = window.encodeURIComponent(params[k]);
}
}
return result;
}
encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号
举个栗子:
document.write(encodeURIComponent("http://www.w3school.com.cn"))
document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
document.write(encodeURIComponent(",/?:@&=+$#"))
//对比
// http%3A%2F%2Fwww.w3school.com.cn
// http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
// %2C%2F%3F%3A%40%26%3D%2B%24%23
断target是否有特定的className:
export function isSpecialSon(target, className){
let flag = false; // 默认为否
let selfTarget = null;
// 闭包 用以公用变量
function fn(_target){
// 判断target是否有特定的className
// 递归的出口
if(flag || !_target){
return;
}
if(!_target.classList){
return;
}
if(_target.classList.contains(className)){
flag = true;
selfTarget = _target;
}else {
// 递归的入口
fn(_target.parentNode);
}
}
fn(target);
return {flag, selfTarget};
}
将对象转成地址栏参数
export function getRequestQuery(query) {
const res = [];
Object.entries(query).forEach(o => res.push(`${o[0]}=${o[1]}`));
return res.join('&');
}
let obj={
key:13,
value:"hhhh",
info:"users"
};
console.log(getRequestQuery(obj));
// key=13&value=hhhh&info=users