目錄
- 1. 型別檢查小工具
- 2. 檢查是否為空
- 3. 獲取串列最后一項
- 4. 帶有范圍的亂數生成器
- 5. 隨機 ID 生成器
- 6. 創建一個范圍內的數字
- 7. 格式化 JSON 字串,stringify 任何內容
- 8. 順序執行 promise
- 9. 輪詢資料
- 10. 等待所有 promise 完成
- 11. 交換陣列值的位置
- 12. 條件物件鍵
- 13. 使用變數作為物件鍵
- 14. 檢查物件里的鍵
- 15. 洗掉陣列重復項
- 16. 在 ArrayforEach 中執行“break”和“continue”
- 17. 使用別名和默認值來銷毀
- 18. 可選鏈和空值合并
- 19. 用函式擴展類
- 20. 擴展建構式
- 21. 回圈任何內容有時,你需要回圈任何可迭代的內容(Set、Map、Object、Array、String 等),這個非常簡單的 forEach 函式工具就可以做到這一點,如果回呼回傳 true,它將退出回圈,
- 22. 使函式引數為 required
- 23. 創建模塊或單例
- 24. 深度克隆物件開發人員通常會安裝一些類似“lodash”的庫來執行這一操作,但使用純 JavaScript 來實作確實也很容易,這是一個簡單的遞回函式:只要是一個物件,就使用函式的構造器將其重新初始化為一個克隆,然后對所有屬性重復該程序,
- 25. 深度凍結物件
寫代碼的時候總有一些東西是會重復出現的,次數多了你就會想找找捷徑了,這類問題中有很大一部分解決起來甚至連庫都不用裝,下面就是我多年來收集的前 25 個捷徑和小技巧,
1. 型別檢查小工具
JavaScript 不是強型別語言,對此我推薦的最佳解決方案是 TypeScript,但有時你只是想要一個簡單的型別檢查,這種時候 JavaScript 允許你使用“typeof”關鍵字,
“typeof”的問題在于,將其用于某些原語和函式時效果很好,但對于陣列和物件來說,由于它們都被視為“物件”,因此很難把握它們之間的區別,
const isOfType = (() => {
// create a plain object with no prototype
const type = Object.create(null);
// check for null type
type.null = x => x === null;
// check for undefined type
type.undefined = x => x === undefined;
// check for nil type. Either null or undefined
type.nil = x => type.null(x) || type.undefined(x);
// check for strings and string literal type. e.g: 's', "s", `str`, new String()
type.string = x => !type.nil(x) && (typeof x === 'string' || x instanceof String);
// check for number or number literal type. e.g: 12, 30.5, new Number()
type.number = x => !type.nil(x)
&& (// NaN & Infinity have typeof "number" and this excludes that
(!isNaN(x) && isFinite(x)
&& typeof x === 'number'
) || x instanceof Number);
// check for boolean or boolean literal type. e.g: true, false, new Boolean()
type.boolean = x => !type.nil(x) && (typeof x === 'boolean' || x instanceof Boolean);
// check for array type
type.array = x => !type.nil(x) && Array.isArray(x);
// check for object or object literal type. e.g: {}, new Object(), Object.create(null)
type.object = x => ({}).toString.call(x) === '[object Object]';
// check for provided type instance
type.type = (x, X) => !type.nil(x) && x instanceof X;
// check for set type
type.set = x => type.type(x, Set);
// check for map type
type.map = x => type.type(x, Map);
// check for date type
type.date = x => type.type(x, Date);
return type;
})();
2. 檢查是否為空
有時你需要知道某些內容是否為空,并根據結果決定要使用的方法,例如檢查長度、大小或是否包含任何子元素,下面這個工具打包了這些功能,你可以用它檢查 String、Object、Array、Map 和 Set 的大小,
function isEmpty(x) {
if(Array.isArray(x)
|| typeof x === 'string'
|| x instanceof String
) {
return x.length === 0;
}
if(x instanceof Map || x instanceof Set) {
return x.size === 0;
}
if(({}).toString.call(x) === '[object Object]') {
return Object.keys(x).length === 0;
}
return false;
}
3. 獲取串列最后一項
其他語言里這個功能被做成了可以在陣列上呼叫的方法或函式,但在 JavaScript 里面,你得自己做點作業,
function lastItem(list) {
if(Array.isArray(list)) {
return list.slice(-1)[0];
}
if(list instanceof Set) {
return Array.from(list).slice(-1)[0];
}
if(list instanceof Map) {
return Array.from(list.values()).slice(-1)[0];
}
}
4. 帶有范圍的亂數生成器
有時你需要生成亂數,但希望這些數字在一定范圍內,那就可以用這個工具,
function randomNumber(max = 1, min = 0) {
if(min >= max) {
return max;
}
return Math.floor(Math.random() * (max - min) + min);
}
5. 隨機 ID 生成器
有時你只是需要一些 ID?除非你要的是更復雜的 ID 生成器(例如 UUID),否則用不著為此安裝什么新庫,下面這個選項足夠了,你可以從當前時間(以毫秒為單位)或特定的整數和增量開始生成,也可以從字母生成 ID,
// create unique id starting from current time in milliseconds
// incrementing it by 1 everytime requested
const uniqueId = (() => {
const id = (function*() {
let mil = new Date().getTime();
while (true)
yield mil += 1;
})();
return () => id.next().value;
})();
// create unique incrementing id starting from provided value or zero
// good for temporary things or things that id resets
const uniqueIncrementingId = ((lastId = 0) => {
const id = (function*() {
let numb = lastId;
while (true)
yield numb += 1;
})()
return (length = 12) => `${id.next().value}`.padStart(length, '0');
})();
// create unique id from letters and numbers
const uniqueAlphaNumericId = (() => {
const heyStack = '0123456789abcdefghijklmnopqrstuvwxyz';
const randomInt = () => Math.floor(Math.random() * Math.floor(heyStack.length))
return (length = 24) => Array.from({length}, () => heyStack[randomInt()]).join('');
})();
6. 創建一個范圍內的數字
Python 里我很喜歡的一個功能是 range 函式,而在 JavaScript 里我經常需要自己寫這個功能,下面是一個簡單的實作,非常適合 for…of 回圈以及需要特定范圍內數字的情況,
function range(maxOrStart, end = null, step = null) {
if(!end) {
return Array.from({length: maxOrStart}, (_, i) => i)
}
if(end <= maxOrStart) {
return [];
}
if(step !== null) {
return Array.from(
{length: Math.ceil(((end - maxOrStart) / step))},
(_, i) => (i * step) + maxOrStart );
}
return Array.from(
{length: Math.ceil((end - maxOrStart))},
(_, i) => i + maxOrStart );
}
7. 格式化 JSON 字串,stringify 任何內容
我在使用 NodeJs 將物件記錄到控制臺時經常使用這種方法,JSON.stringify 方法需要第三個引數,該引數必須有多個空格以縮進行,第二個引數可以為 null,但你可以用它來處理 function、Set、Map、Symbol 之類 JSON.stringify 方法無法處理或完全忽略的內容,

const stringify = (() => {
const replacer = (key, val) => {
if(typeof val === 'symbol') {
return val.toString();
}
if(val instanceof Set) {
return Array.from(val);
}
if(val instanceof Map) {
return Array.from(val.entries());
}
if(typeof val === 'function') {
return val.toString();
}
return val;
}
return (obj, spaces = 0) => JSON.stringify(obj, replacer, spaces)
})();
8. 順序執行 promise
如果你有一堆異步或普通函式都回傳 promise,要求你一個接一個地執行,這個工具就會很有用,它會獲取函式或 promise 串列,并使用陣列 reduce 方法按順序決議它們,
const asyncSequentializer = (() => {
const toPromise = (x) => {
if(x instanceof Promise) { // if promise just return it
return x;
}
if(typeof x === 'function') {
// if function is not async this will turn its result into a promise
// if it is async this will await for the result
return (async () => await x())();
}
return Promise.resolve(x)
}
return (list) => {
const results = [];
return list
.reduce((lastPromise, currentPromise) => {
return lastPromise.then(res => {
results.push(res); // collect the results
return toPromise(currentPromise);
});
}, toPromise(list.shift()))
// collect the final result and return the array of results as resolved promise
.then(res => Promise.resolve([...results, res]));
}
})();
9. 輪詢資料
如果你需要持續檢查資料更新,但系統中沒有 WebSocket,則可以使用這個工具來執行操作,它非常適合上傳檔案時,想要持續檢查檔案是否已完成處理的情況,或者使用第三方 API(例如 dropbox 或 uber)并且想要持續檢查程序是否完成或騎手是否到達目的地的情況,
async function poll(fn, validate, interval = 2500) {
const resolver = async (resolve, reject) => {
try { // catch any error thrown by the "fn" function
const result = await fn(); // fn does not need to be asynchronous or return promise
// call validator to see if the data is at the state to stop the polling
const valid = validate(result);
if (valid === true) {
resolve(result);
} else if (valid === false) {
setTimeout(resolver, interval, resolve, reject);
} // if validator returns anything other than "true" or "false" it stops polling
} catch (e) {
reject(e);
}
};
return new Promise(resolver);
}
10. 等待所有 promise 完成
這個算不上是代碼解決方案,更多是對 Promise API 的強化,這個 API 在不斷進化,以前我還為“allSettled”“race”和“any”做了代碼實作,現在直接用 API 的就好了,

11. 交換陣列值的位置
ES6 開始,從陣列中的不同位置交換值變得容易多了,這個做起來不難,但是了解一下也不錯,

12. 條件物件鍵
我最喜歡這條技巧了,我在使用 React 更新狀態時經常用它,你可以將條件包裝在括號中來有條件地將一個鍵插入一個 spread 物件,

13. 使用變數作為物件鍵
當你有一個字串變數,并想將其用作物件中的鍵以設定一個值時可以用它,

14. 檢查物件里的鍵
這是一個很好的技巧,可以幫助你檢查物件鍵,

15. 洗掉陣列重復項
陣列中經常有重復的值,你可以使用 Set 資料結構來消除它,它適用于許多資料型別,并且 set 有多種檢查相等性的方法,很好用,對于不同實體或物件的情況,你還是可以使用 Set 來跟蹤特定事物并過濾出重復的物件,

16. 在 ArrayforEach 中執行“break”和“continue”
我真的很喜歡使用陣列“.forEach”方法,但有時我需要提早退出或繼續進行下一個回圈,而不想用 for...loop,你可以復制“continue”陳述句行為來提前回傳,但如果要復制“break”行為,則需要使用陣列“.some”方法,

17. 使用別名和默認值來銷毀
Destructuring(銷毀)是 JavaScript 最好用的功能之一,而且你可以使用“冒號”設定別名,并使用“等號”設定屬性默認值,

18. 可選鏈和空值合并
深入檢查物件屬性并處理 null 和 undefined 值時,你可以使用幾個非常好用的 JavaScript 功能來解決常見的問題,

19. 用函式擴展類
我經常對別人講,JavaScript 類只是建構式和底層的原型,不是像 Java 中那樣的真實概念,一個證據是,你可以只使用一個建構式來擴展一個類,在私有內容里這個很好用,在類里“#”這些看著很奇怪,并且用于 babel 或 WebPack 時,編譯出來的代碼更少,

20. 擴展建構式
類的一個問題是你只能擴展一個其他類,使用建構式,你可以使用多個建構式來構成一個函式,這樣就會靈活多了,你可以使用函式原型的.apply 或.call 方法來實作,你甚至可以只擴展函式的一部分,只要它是一個物件即可,

21. 回圈任何內容有時,你需要回圈任何可迭代的內容(Set、Map、Object、Array、String 等),這個非常簡單的 forEach 函式工具就可以做到這一點,如果回呼回傳 true,它將退出回圈,
function forEach(list, callback) {
const entries = Object.entries(list);
let i = 0;
const len = entries.length;
for(;i < len; i++) {
const res = callback(entries[i][1], entries[i][0], list);
if(res === true) break;
}
}
22. 使函式引數為 required
這是一種確保函式呼叫了完成作業所需內容的絕佳方法,你可以使用默認引數值的特性來呼叫函式,然后就會拋出一個錯誤,如果呼叫該函式時帶上了它需要的值,則該值將替換該函式,并且什么也不會發生,使用 undefined 呼叫也有相同的效果,
function required(argName = 'param') {
throw new Error(`"${argName}" is required`)
}
function iHaveRequiredOptions(arg1 = required('arg1'), arg2 = 10) {
console.log(arg1, arg2)
}
iHaveRequiredOptions(); // throws "arg1" is required
iHaveRequiredOptions(12); // prints 12, 10
iHaveRequiredOptions(12, 24); // prints 12, 24
iHaveRequiredOptions(undefined, 24); // throws "arg1" is required
23. 創建模塊或單例
很多時候,你需要在加載時初始化某些內容,設定它需要的各種事物,然后就可以在應用程式中到處使用它,而無需再做什么補充作業,你可以使用 IIFE 函式來做到這一點,這個函式太好用了,這種模塊模式用來隔離事物非常好用,它可以只暴露需要互動的內容,

24. 深度克隆物件開發人員通常會安裝一些類似“lodash”的庫來執行這一操作,但使用純 JavaScript 來實作確實也很容易,這是一個簡單的遞回函式:只要是一個物件,就使用函式的構造器將其重新初始化為一個克隆,然后對所有屬性重復該程序,
const deepClone = obj => {
let clone = obj;
if (obj && typeof obj === "object") {
clone = new obj.constructor();
Object.getOwnPropertyNames(obj).forEach(
prop => (clone[prop] = deepClone(obj[prop]))
);
}
return clone;
};
25. 深度凍結物件
如果你喜歡不變性,那么這個工具你一定要常備,
const deepClone = obj => {
let clone = obj;
if (obj && typeof obj === "object") {
clone = new obj.constructor();
Object.getOwnPropertyNames(obj).forEach(
prop => (clone[prop] = deepClone(obj[prop]))
);
}
return clone;
};
延伸閱讀
https://beforesemicolon.medium.com/25-javascript-code-solutions-utility-tricks-you-need-to-know-about-3023f7ed993e
作者:Before Semicolon
譯者:王強
策劃:李俊辰
鏈接:你應該了解的25個JS技巧
來源:微信公眾號
著作權歸作者所有,商業轉載請聯系作者獲得授權,非商業轉載請注明出處,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/245123.html
標籤:其他
上一篇:繪制微信小程式驗證碼
