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