单行代码能实现哪些功能
1. 解析 url
中的参数
const parseSearch = (url = window.location.href) => {
return url.split('#')[0].match(/\?(.+)/)[1].split('&').reduce((json, item) => {
let [key, value] = item.split('=');
value = decodeURI(value);
if (/(^[1-9]\d*\.?\d*$)|(^0\.\d*$)/.test(value)) value = Number(value);
json[key] = value;
return json;
}, {});
};
const url = 'https://www.baidu.com?num=9.25&q=%E4%B8%80%E4%B8%AA%E6%95%B0%E7%BB%84%E6%89%BE%E5%B3%B0%E5%80%BC+logn&qs=n&form=QBRE&sp=-1&pq=%E4%B8%80%E4%B8%AA%E6%95%B0%E7%BB%84%E6%89%BE%E5%B3%B0%E5%80%BC+lo&sc=0-10&sk=&cvid=45F0B8049DC64FBFA8AA20FAF7149D59#tag';
console.log(parseSearch(url));
2. 生成随机HEX颜色
const randomInt = (max, n) => Array(n).fill().map(() => Math.random() * max | 0); // 生成一组随机整数
const rgbToHex = (r, g, b) => '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); // RGB转为十六进制HEX值
const randomHex = () => rgbToHex(...randomInt(256, 3)); // 生成随机HEX值
console.log(randomHex());