9 個JavaScript 技巧
1. 生成指定范圍的數字
在某些情況下,我們會創建一個處在兩個數之間的數組。假設我們要判斷某人的生日是否在某個范圍的年份內,那么下面是實現它的一個很簡單的方法:
- let start = 1900, end = 2000;
- [...new Array(end + 1).keys()].slice(start);
- // [ 1900, 1901, ..., 2000]
- // 還有這種方式,但對于很的范圍就不太穩定
- Array.from({ length: end - start + 1 }, (_, i) => start + i);
2. 使用值數組作為函數的參數
在某些情況下,我們需要將值收集到數組中,然后將其作為函數的參數傳遞。使用 ES6,可以使用擴展運算符(...)并從[arg1, arg2] > (arg1, arg2)中提取數組:
- const parts = {
- first: [0, 2],
- second: [1, 3],
- }
- ["Hello", "World", "JS", "Tricks"].slice(...parts.second)
- // ["World", "JS"]
3. 將值用作 Math 方法的參數
當我們需要在數組中使用Math.max或Math.min來找到最大或者最小值時,我們可以像下面這樣進行操作:
- const elementsHeight = [...document.body.children].map(
- el => el.getBoundingClientRect().y
- );
- Math.max(...elementsHeight);
- // 474
- const numbers = [100, 100, -1000, 2000, -3000, 40000];
- Math.min(...numbers);
- // -3000
4. 合并/展平數組中的數組
Array 有一個很好的方法,稱為Array.flat,它是需要一個depth參數,表示數組嵌套的深度,默認值為1。但是,如果我們不知道深度怎么辦,則需要將其全部展平,只需將Infinity作為參數即可
- const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]
- arrays.flat(Infinity)
- // [ 10, 50, 100, 2000, 3000, 40000 ]
5. 防止代碼崩潰
在代碼中出現不可預測的行為是不好的,但是如果你有這種行為,你需要處理它。
例如,常見錯誤TypeError,試獲取undefined/null等屬性,就會報這個錯誤。
- const found = [{ name: "Alex" }].find(i => i.name === 'Jim')
- console.log(found.name)
- // TypeError: Cannot read property 'name' of undefined
我們可以這樣避免它:
- const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}
- console.log(found.name)
- // undefined
6. 傳遞參數的好方法
對于這個方法,一個很好的用例就是styled-components,在ES6中,我們可以將模板字符中作為函數的參數傳遞而無需使用方括號。如果要實現格式化/轉換文本的功能,這是一個很好的技巧:
- const makeList = (raw) =>
- raw
- .join()
- .trim()
- .split("\n")
- .map((s, i) => `${i + 1}. ${s}`)
- .join("\n");
- makeList`
- Hello, World
- Hello, World
- `;
- // 1. Hello,World
- // 2. World,World
7. 交換變量
使用解構賦值語法,我們可以輕松地交換變量 使用解構賦值語法:
- let a = "hello"
- let b = "world"
- // 錯誤的方式
- a = b
- b = a
- // { a: 'world', b: 'world' }
- // 正確的做法
- [a, b] = [b, a]
- // { a: 'world', b: 'hello' }
8. 按字母順序排序
需要在跨國際的項目中,對于按字典排序,一些比較特殊的語言可能會出現問題,如下所示:
- // 錯誤的做法
- ["a", "z", "ä"].sort((a, b) => a - b);
- // ['a', 'z', 'ä']
- // 正確的做法
- ["a", "z", "ä"].sort((a, b) => a.localeCompare(b));
- // [ 'a', 'ä', 'z' ]
localeCompare() :用本地特定的順序來比較兩個字符串。
9. 隱藏隱私
最后一個技巧是屏蔽字符串,當你需要屏蔽任何變量時(不是密碼),下面這種做法可以快速幫你做到:
- const password = "hackme";
- password.substr(-3).padStart(password.length, "*");
- // ***kme