「必須收藏」周末學(xué)到的 10 個(gè) JS 實(shí)用的小技巧
趁著周末偷偷學(xué)習(xí)的 10 個(gè) JS 實(shí)用小技巧,大家一起來(lái)學(xué)習(xí)一下吧~
同步阻塞法實(shí)現(xiàn)sleep函數(shù)
const sleep = delay => {
const start = new Date().getTime();
while (new Date().getTime() < start + delay) {
continue;
};
};
console.log(1);
sleep(3000);
console.log(2);
利用 new URL 解析 URL
const parseURL = (url = '') => {
const res = new URL(url);
res.queryParams = key => {
if (key) {
return res.searchParams.get(key)
};
const params = {};
const paramGroup = res.search.replace(/^\?/,'').split('&');
paramGroup.forEach(param => {
const [key, val] = param.split('=');
params[key] = val;
});
return params;
};
return res;
};
parseURL('https://www.example.com/a/b?c=1&d=2');
一行代碼實(shí)現(xiàn)星級(jí)評(píng)分
const getRate = (rate = 0) => '★★★★★☆☆☆☆☆'.slice(5 - rate, 10 - rate);
getRate(3);用位運(yùn)算提升效率
// | 取整
let num1 = 1.7;
num1 = num1 | 0;
// >> 取半
let num2 = 6;
num2 = num2 >> 1; // 3
// << 加倍
let num3 = 6;
num3 = num3 << 1; / / 12
// ^ 交換值
let num4 = 10;
let num5 = 20;
num4 ^= num5;
num5 ^= num4;
num4 ^= num5; // num4 === 2, num5 === 1
// & 判斷奇數(shù)
let num6 = 10;
let num7 = 11;
num6 & 1 === 1; // true
num7 & 1 === 1; // false
// ~ 判斷是否存在
const data = '123456';
const key = '3';
const keyIsExist = !!~data.indexOf(key); // true
// 是否 2 的整數(shù)冪
const isPowerOf2 = num => (num & (num - 1)) === 0;
isPowerOf2(8) // true
isPowerOf2(7) // false
判斷是否是千分符字符
const numberIsThousand = str => /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test(str);
numberIsThousand('100,000,000,000') // true
numberIsThousand('100,000,000,00') // false
復(fù)制文本到剪切板
const copyToClipboard = content => {
const clipboardData = window.clipboardData;
if (clipboardData) {
clipboardData.clearData();
clipboardData.setData('Text', content);
return true;
} else if (document.execCommand) {
const el = document.createElement('textarea');
el.value = content;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
return true;
}
return false;
};copyToClipboard('hello world');
一行代碼生成指定長(zhǎng)度的數(shù)組
const List = len => [...new Array(len).keys()];
const list = List(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
判斷數(shù)據(jù)類型
const type = data => {
let toString = Object.prototype.toString;
const dataType =
data instanceof Element
? 'element' // 為了統(tǒng)一DOM節(jié)點(diǎn)類型輸出
: toString
.call(data)
.replace(/\[object\s(.+)\]/, '$1')
.toLowerCase()
return dataType
};
type({}); // object
正則判斷字符重復(fù)次數(shù)不超過(guò)兩次
const strIsRepeatThan2 = (str = '') => /^(?!.*(.).*\1{2})[\da-zA-Z].+$/.test(str);
strIsRepeatThan2('123456'); // true
strIsRepeatThan2('1234566'); // true
strIsRepeatThan2('12345666'); // false
正則匹配可以只有 0 但開(kāi)頭不能是 0 的數(shù)字
const getCorrectNumber = (str = '') => /^(\d|[1-9]\d*)$/.test(str);
getCorrectNumber('0'); // true
getCorrectNumber('011'); // false
getCorrectNumber('101'); // true
評(píng)論
圖片
表情
