// 每日前端夜話 第407篇
// 正文共:1200 字
// 預計閱讀時間:5 分鐘
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)
。web
const parts = {
first: [0, 2],
second: [1, 3],
};
["Hello", "World", "JS", "Tricks"].slice(...parts.second);
// ["World", "JS", "Tricks"]
這個技巧在任何函數中都適用,請繼續看第 3 條。數組
3. 把值數組中的值做爲 Math 方法的參數
當須要在數組中找到數字的最大或最小值時,能夠像下面這樣作:微信
// 查到元素中的 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. 展平嵌套數組
Array 有一個名爲 Array.flat
的方法,它須要一個表示深度的參數來展平嵌套數組(默認值爲 1)。可是若是你不知道深度怎麼辦,這時候只須要將 Infinity
做爲參數便可。另外還有一個很好用的 flatMap 方法。app
const arrays = [[10], 50, [100, [2000, 3000, [40000]]]];
arrays.flat(Infinity);
// [ 10, 50, 100, 2000, 3000, 40000 ]
5. 防止代碼崩潰
若是在代碼中存在不可預測的行爲,後果是難以預料的,因此須要對其進行處理。編輯器
例如當你想要獲取的屬性爲 undefined
或 null
時,會獲得 TypeError
錯誤。ide
若是你的項目代碼不支持可選鏈( 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
不過這要視狀況而定,對於小規模的代碼進行處理徹底沒什麼問題。不須要太多代碼就能夠處理它。flex
6. 傳參的好方法
在 ES6 中能夠把 模板字面量(Template literal) 看成是不帶括號的函數的參數。這在進行格式化或轉換文本的時很是好用。
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
結語
在編碼時還須要保持代碼整潔,平時注意積累在編碼時所使到的技巧,並關注 JavaScript 的新增特性。
長按掃描維碼
關注咱們 獲取更多前端資訊
|最新技術|業界動態|
|學習視頻|源碼資源|
本文分享自微信公衆號 - 前端先鋒(jingchengyideng)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。