11 個對開發(fā)有幫助的 JS 技巧,進(jìn)收藏夾當(dāng)小詞典吧!
本文已經(jīng)過原作者 Orkhan Jafarov 授權(quán)翻譯。
1. 生成一個帶有隨機(jī)數(shù)的列表
- Array.from({ length: 1000 }, Math.random)
- // [ 0.6163093133259432, 0.8877401276499153, 0.4094354756035987, ...] - 1000 items
2.生成一個帶有數(shù)字的列表
- Array.from({ length: 1000 }, (v, i) => i)
- // [0, 1, 2, 3, 4, 5, 6....999]
3. RGB→轉(zhuǎn)換為十六進(jìn)制
- const rgb2hex = ([r, g, b]) =>
- `#${(1 << 24) + (r << 16) + (g << 8) + b}`.toString(16).substr(1);
- rgb2hex([76, 11, 181]);
- // #4c0bb5
4. 轉(zhuǎn)換十六進(jìn)制→RGB
怎么把它轉(zhuǎn)換回去?這是實現(xiàn)該目標(biāo)的一種好方法。
- const hex2rgb = hex =>
- [1, 3, 5].map((h) => parseInt(hex.substring(h, h + 2), 16));
- hex2rgb("#4c0bb5");
- // [76, 11, 181]
5.奇數(shù)或偶數(shù)
使用 位 運算的方式:
- const value = 232;
- if (value & 1) console.log("odd");
- else console.log("even");
- // even
6.檢查有效的 URL
- const isValidURL = (url) => {
- try {
- new URL(url);
- return true;
- } catch (error) {
- return false;
- }
- }
- isValidURL('https://segmentfault.com/u/minnanitkong/articles')
- // true
- isValidURL("https//invalidto");
- // false
7.距離過去到現(xiàn)在時間表示
有時我們需要打印6分鐘前的日期,但不希望很大的庫來完成。這里有一個小片段可以做到這一點:
- const fromAgo = (date) => {
- const ms = Date.now() - date.getTime();
- const seconds = Math.round(ms / 1000);
- const minutes = Math.round(ms / 60000);
- const hours = Math.round(ms / 3600000);
- const days = Math.round(ms / 86400000);
- const months = Math.round(ms / 2592000000);
- const years = Math.round(ms / 31104000000);
- switch (true) {
- case seconds < 60:
- return `${seconds} second(s) ago"`;
- case minutes < 60:
- return `${minutes} minute(s) ago"`;
- case hours < 24:
- return `${hours} hour(s) ago"`;
- case days < 30:
- return `${days} day(s) ago`;
- case months < 12:
- return `${months} month(s) ago`;
- default:
- return `${years} year(s) ago`;
- }
- };
- const createdAt = new Date(2021, 0, 5);
- fromAgo(createdAt); // 14 day(s) ago;
8. 用參數(shù)生成路徑
我們在處理路線/路徑時常做很多工作,我們總是需要對其進(jìn)行操作。當(dāng)我們需要生成帶有參數(shù)的路徑以將瀏覽器推送到那里時,generatePath 可以幫助我們!
- const generatePath = (path, obj) =>
- path.replace(/(:[a-z]+)/g, (v) => obj[v.substr(1)]);
- const route = "/app/:page/:id";
- generatePath(route, {
- page: "products",
- id: 85,
- });
- // /app/products/123
9.從路徑獲取參數(shù)
- const getPathParams = (path, pathMap, serializer) => {
- path = path.split("/");
- pathMap = pathMap.split("/");
- return pathMap.reduce((acc, crr, i) => {
- if (crr[0] === ":") {
- const param = crr.substr(1);
- acc[param] = serializer && serializer[param]
- ? serializer[param](path[i])
- : path[i];
- }
- return acc;
- }, {});
- };
- getPathParams("/app/products/123", "/app/:page/:id");
- // { page: 'products', id: '123' }
- getPathParams("/items/2/id/8583212", "/items/:category/id/:id", {
- category: v => ['Car', 'Mobile', 'Home'][v],
- id: v => +v
- });
- // { category: 'Home', id: 8583212 }
10.用查詢字符串生成路徑
- const getQueryParams = url =>
- url.match(/([^?=&]+)(=([^&]*))/g).reduce((total, crr) => {
- const [key, value] = crr.split("=");
- total[key] = value;
- return total;
- }, {});
- getQueryParams("/user?name=Orkhan&age=30");
- // { name: 'Orkhan', age: '30' }
我是小智,我要去刷碗了,我們下期見~
作者:Orkhan Jafarov 譯者:前端小智 來源: dev
原文:https://dev.to/11-javascript-tips-and-tricks-to-code-like-a-superhero-vol-2-mp6
本文轉(zhuǎn)載自微信公眾號「大遷世界」,作者大遷世界。轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號。