JS实际开发项目中的编码小技巧及面试手撕系列
一.Github开源JavaScript风格规范
1.Airbnb JavaScript Style Guide()
2.JavaScript 风格指南
二.ES系列中30个常用的JavaScript简写技巧
三.JS逻辑优雅处理技巧
1.面试官问:如何拆解URL参数中queryString
入参格式参考:
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
出参格式参考:
const result = {
a: '1', b: '2', c: 'xx', d: '' };
// 拆解URL参数中queryString,返回一个 key - value 形式的 object
解答一:正则
const queryString = (str)=>{
const obj = {
}
str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v))
return obj
}
解答二:URLSearchParams
function getParams(u: URL) {
const s = new URLSearchParams(u.search)
const obj = {
}
s.forEach((v, k) => (obj[k] = v))
return obj
}
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
getParams(new URL(url))
解答三:字符串分割
字符串分割拿到参数相关的字符串,再做类型转换
const dismantle = (url) => {
const aimUrl = url.split('?').pop().split('#').shift().split('&');
const res = {
};
aimUrl.forEach(item => {
const [key, val] = item.split('=');
res[key] = val;
});
return res;
}
四.如何让你的代码变得干净优雅且可维护
(一).关于命名
1.使用有意义且易读的变量名(见名知义)
👎 const yyyymmdstr = moment().format("YYYY/MM/DD");
👍 const currentDate = moment().format("YYYY/MM/DD");
2.使用有意义的变量代替数组下标
👎
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
address.match(cityZipCodeRegex)[1],
address.match(cityZipCodeRegex)[2]
);
👍
const address