工具
生成 UUID
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
// Examples
//代码效果参考:http://www.cmjzs.com/sitemap/post1.html
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
解析 cookie
const parseCookie = (str) =>
str
.split(";")
.map((v) => v.split("="))
.reduce((acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
parseCookie("foo=bar; equation=E%3Dmc%5E2");
// { foo: 'bar', equation: 'E=mc^2' }
获取网址参数
const getURLParameters = (url) =>
(url.match(/([^?=&]+)(=([^&]))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
),
{}
getURLParameters("google.com"); // {}
getURLParameters("http://www.cmjzs.com/sitemap/post1.html");
// {name: 'Adam', surname: 'Smith'}
复制到剪切板
以下方式仅在用户执行操作时有效,如:click 事件
const copyToClipboard = (str) => {
const el = document.createElement("textarea");
el.value = str;
el.setAttribute("readonly", "");
el.style.position = "absolute";
el.style.left = "-9999px";
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
copyToClipboard("Lorem ipsum"); // 'Lorem ipsum' copied to clipboard.
简版 jquery 选择器
// 仅选中第一个元素
const $ = document.querySelector.bind(document);
// 选中所有
const $$ = document.querySelectorAll.bind(document); const mainContent = $(".main-content"); const externalLinks = $$('a[target="_blank"]');
多线程执行函数
const runAsync = (fn) => {
const worker = new Worker(
URL.createObjectURL(new Blob([postMessage((${fn})());
]), {
type: "application/javascript; charset=utf-8",
})
return new Promise((res, rej) => {
worker.onmessage = ({ data }) => {
res(data), worker.terminate();
};
worker.onerror = (err) => {
rej(err), worker.terminate();
});
const longRunningFunction = () => {
let result = 0;
for (let i = 0; i < 1000; i++)
for (let j = 0; j < 700; j++)
for (let k = 0; k < 300; k++) result = result + i + j + k;
return result;
/
NOTE: Since the function is running in a different context, closures are not supported.
The function supplied to runAsync
gets stringified, so everything becomes literal.
All variables and functions must be defined inside.
/
runAsync(longRunningFunction).then(console.log); // 209685000000
runAsync(() => 10 * 3).then(console.log); // 1000
let outsideVariable = 50;
runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'