對 JavaScript 開發者非常有用的 10 個技巧
你可能錯過這些非常有用的技巧。
翻譯自 10 Super Useful Tricks for JavaScript Developers,作者 Mahdhi Rezvi。
我們知道,JavaScript 這門語言正在高速發展中。伴隨著 ES2020,又有很多很棒的功能加入。老實說,您可以通過許多不同的方式編寫代碼。實現同樣一個功能,有的代碼很長而有的卻很短。你可以通過一些小技巧來讓你的代碼更干凈清晰。下面這些小技巧肯定對你接下來的開發工作有所用處。
函數參數驗證器
JavaScript 允許你對函數參數設置默認值。通過這個特性,我們可以實現一個小技巧來驗證函數參數。
- const isRequired = () => { throw new Error('param is required'); };
- const print = (num = isRequired()) => { console.log(`printing ${num}`) };
- print(2); //printing 2
- print(); // error
- print(null); //printing null
格式化 JSON 代碼
你肯定對 JSON.stringify 非常熟悉了,但是你知道嗎,你也可以通過 stringify 方法格式化你的代碼。其實這很簡單。
stringify 方法有三個參數,分別是 value replacer 和 space。后面兩個參數是可選的,所以我們平常也不會用到它們。想要縮進輸出的代碼,我們可以使用2個空格 ,或者4個空格。
- console.log(JSON.stringify({ name:"John", Age:23 }, null, ' '));
- >>>
- {
- "name": "John",
- "Age": 23
- }
對數組去重
以往對數組去重我們會使用 filter 函數來過濾掉重復的值。但是現在我們可以使用新的 Set 特性來過濾。非常簡單:
- let uniqueArray = [...new Set([1, 2, 3, 3, 3, "school", "school", 'ball', false, false, true, true])];
- >>> [1, 2, 3, "school", "ball", false, true]
去除數組中的 Boolean(v) 為 false 的值
有時候你想刪除數組中 Boolean(v) 為 false 的值。在 JavaScript 中只有以下 6 種:
- undefined
- null
- NaN
- 0
- 空字符串
- false
去除這些值最簡單的辦法是使用下面的方法:
- array.filter(Boolean)
如果你想先做一些更改然后再過濾,你可以用下面的方法。要記住,原始數組 array 是一直沒變的,返回的是一個新數組。
- array
- .map(item => {
- // Do your changes and return the new item
- })
- .filter(Boolean);
同時合并多個對象
如果需要同時合并多個對象或者類,可以用下面這種方法。
- const user = {
- name: "John Ludwig",
- gender: "Male",
- };
- const college = {
- primary: "Mani Primary School",
- secondary: "Lass Secondary School",
- };
- const skills = {
- programming: "Extreme",
- swimming: "Average",
- sleeping: "Pro",
- };
- const summary = { ...user, ...college, ...skills };
- >>>
- {
- name: 'John Ludwig',
- gender: 'Male',
- primary: 'Mani Primary School',
- secondary: 'Lass Secondary School',
- programming: 'Extreme',
- swimming: 'Average',
- sleeping: 'Pro'
- }
三個點也叫擴展操作符。
對數字數組排序
JavaScript 數組有一個原生的排序方法 arr.sort。 這個排序方法默認把數組元素轉換成字符串,并對其進行字典序排序。這個默認行為會在排序數字數組時出現問題,所以下面有一個辦法來處理這個問題。
- [0, 10, 4, 9, 123, 54, 1].sort()
- >>> [0, 1, 10, 123, 4, 54, 9]
- [0, 10, 4, 9, 123, 54, 1].sort((a,b) => a-b);
- >>> [0, 1, 4, 9, 10, 54, 123]
禁用右鍵
有時候你可能想要禁止用戶點擊右鍵。雖然這個需求很少見,但是可能派的上用場。
- <body oncontextmenu="return false">
- <div></div>
- </body>
這個簡單的代碼片段就可以禁止用戶點擊右鍵了。
解構時重命名
解構賦值是 JavaScript 的一個特性,它允許直接從數組或者對象中獲取值,而不需要繁瑣的聲明變量再賦值。對對象來講,我們可以通過下面這種方式來給屬性名重新定義一個名字。
- const object = { number: 10 };
- // Grabbing number
- const { number } = object;
- // Grabbing number and renaming it as otherNumber
- const { number: otherNumber } = object;
- console.log(otherNumber); // 10
獲取數組中的最后一項
如果你想獲取數組中的最后一項,你可以使用 slice 函數,同時帶上一個負數作為參數。
- let array = [0, 1, 2, 3, 4, 5, 6, 7]
- console.log(array.slice(-1));
- >>>[7]
- console.log(array.slice(-2));
- >>>[6, 7]
- console.log(array.slice(-3));
- >>>[5, 6, 7]
等待 Promises 全部執行完成
有時候你可能需要等待幾個 promise 都執行完然后進行后面的操作。你可以使用 Promise.all 來并行執行這些 promise。
- const PromiseArray = [
- Promise.resolve(100),
- Promise.reject(null),
- Promise.resolve("Data release"),
- Promise.reject(new Error('Something went wrong'))];
- Promise.all(PromiseArray)
- .then(data => console.log('all resolved! here are the resolve values:', data))
- .catch(err => console.log('got rejected! reason:', err))
要注意,只要 Promise.all 中有一個是 rejected 狀態時,其會立即停止執行并拋出異常。
如果你想忽略 resolved 或者 rejected 狀態,你可以使用 Promise.allSettled。這個是 ES2020 的一個新特性。
- const PromiseArray = [
- Promise.resolve(100),
- Promise.reject(null),
- Promise.resolve("Data release"),
- Promise.reject(new Error("Something went wrong")),
- ];
- Promise.allSettled(PromiseArray)
- .then((res) => {
- console.log("here", res);
- })
- .catch((err) => console.log(err));
- >>>
- here [
- { status: 'fulfilled', value: 100 },
- { status: 'rejected', reason: null },
- { status: 'fulfilled', value: 'Data release' },
- {
- status: 'rejected',
- reason: Error: Something went wrong
- at Object.<anonymous>
- at Module._compile (internal/modules/cjs/loader.js:1200:30)
- at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
- at Module.load (internal/modules/cjs/loader.js:1049:32)
- at Function.Module._load (internal/modules/cjs/loader.js:937:14)
- at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
- at internal/main/run_main_module.js:17:4