8個寫JavaScript代碼的小技巧
在編碼時還需要保持代碼整潔,平時注意積累在編碼時所使到的技巧,并關注 JavaScript 的新增特性。
1. 生成指定區(qū)間內(nèi)的數(shù)字
有時候需要創(chuàng)建在某個數(shù)字范圍內(nèi)的數(shù)組。比如在選擇生日時。以下是最簡單的實現(xiàn)方法。
- let start = 1900,
- end = 2000;
- [...new Array(end + 1).keys()].slice(start);
- // [ 1900, 1901, ..., 2000]
- // 也可以這樣,但是大范圍結(jié)果不穩(wěn)定
- Array.from({ length: end - start + 1 }, (_, i) => start + i);
2. 把值數(shù)組中的值作為函數(shù)的參數(shù)
有時候我們需要先把值放到數(shù)組中,然后再作為函數(shù)的參數(shù)進行傳遞。使用 ES6 語法可以只憑借擴展運算符(...)就可以把值從數(shù)組中提取出來:[arg1,arg2] => (arg1,arg2)。
- const parts = {
- first: [0, 2],
- second: [1, 3],
- };
- ["Hello", "World", "JS", "Tricks"].slice(...parts.second);
- // ["World", "JS", "Tricks"]
這個技巧在任何函數(shù)中都適用,請繼續(xù)看第 3 條。
3. 把值數(shù)組中的值作為 Math 方法的參數(shù)
當需要在數(shù)組中找到數(shù)字的最大或最小值時,可以像下面這樣做:
- // 查到元素中的 y 位置最大的那一個值
- const elementsHeight = [...document.body.children].map(
- el => el.getBoundingClientRect().y
- );
- Math.max(...elementsHeight);
- // 輸出最大的那個值
- const numbers = [100, 100, -1000, 2000, -3000, 40000];
- Math.min(...numbers);
- // -3000
4. 展平嵌套數(shù)組
Array 有一個名為 Array.flat 的方法,它需要一個表示深度的參數(shù)來展平嵌套數(shù)組(默認值為 1)。但是如果你不知道深度怎么辦,這時候只需要將 Infinity 作為參數(shù)即可。另外還有一個很好用的 flatMap 方法。
- const arrays = [[10], 50, [100, [2000, 3000, [40000]]]];
- arrays.flat(Infinity);
- // [ 10, 50, 100, 2000, 3000, 40000 ]
5. 防止代碼崩潰
如果在代碼中存在不可預測的行為,后果是難以預料的,所以需要對其進行處理。
例如當你想要獲取的屬性為 undefined 或 null 時,會得到 TypeError 錯誤。
如果你的項目代碼不支持可選鏈( optional chaining)的話,可以這樣做:
- 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
不過這要視情況而定,對于小規(guī)模的代碼進行處理完全沒什么問題。不需要太多代碼就可以處理它。
6. 傳參的好方法
在 ES6 中可以把 模板字面量(Template literal) 當作是不帶括號的函數(shù)的參數(shù)。這在進行格式化或轉(zhuǎn)換文本的時非常好用。
- const makeList = (raw) =>
- raw
- .join()
- .trim()
- .split("\n")
- .map((s, i) => `${i + 1}. ${s}`)
- .join("\n");
- makeList`
- Hello, World
- Hello, World
- `;
- // 1. Hello
- // 2. 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. 遮蔽字符串
某些時候我們需要遮蔽字符串的一部分,當然不只是對密碼做這種操作。下面代碼中通過 substr(-3) 得到字符串的一部分,即從字符串末尾開始往前 3 個字符,然后再用你喜歡的字符填充剩余的位置(比如說用 *)
- const password = "hackme";
- password.substr(-3).padStart(password.length, "*");
- // ***kme