做者:Orkhan Jafarov翻譯:瘋狂的技術宅javascript
原文:https://dev.to/gigantz/9-java...前端
未經容許嚴禁轉載java
有時候須要建立在某個數字範圍內的數組。好比在選擇生日時。如下是最簡單的實現方法。程序員
let start = 1900, end = 2000; [...new Array(end + 1).keys()].slice(start); // [ 1900, 1901, ..., 2000] // 也能夠這樣,可是大範圍結果不穩定 Array.from({ length: end - start + 1 }, (_, i) => start + i);
有時候咱們須要先把值放到數組中,而後再做爲函數的參數進行傳遞。使用 ES6 語法能夠只憑借擴展運算符(...
)就能夠把值從數組中提取出來: [arg1,arg2] => (arg1,arg2)
。面試
const parts = { first: [0, 2], second: [1, 3], }; ["Hello", "World", "JS", "Tricks"].slice(...parts.second); // ["World", "JS", "Tricks"]
這個技巧在任何函數中都適用,請繼續看第 3 條。segmentfault
當須要在數組中找到數字的最大或最小值時,能夠像下面這樣作:數組
// 查到元素中的 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
Array 有一個名爲 Array.flat
的方法,它須要一個表示深度的參數來展平嵌套數組(默認值爲 1)。可是若是你不知道深度怎麼辦,這時候只須要將 Infinity
做爲參數便可。另外還有一個很好用的 flatMap 方法。服務器
const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]; arrays.flat(Infinity); // [ 10, 50, 100, 2000, 3000, 40000 ]
若是在代碼中存在不可預測的行爲,後果是難以預料的,因此須要對其進行處理。微信
例如當你想要獲取的屬性爲 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
不過這要視狀況而定,對於小規模的代碼進行處理徹底沒什麼問題。不須要太多代碼就能夠處理它。
在 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
經過解構賦值語法,能夠輕鬆地交換變量。
let a = "hello"; let b = "world"; // 錯誤 ❌ a = b b = a // { a: 'world', b: 'world' } // 正確 ✅ [a, b] = [b, a]; // { a: 'world', b: 'hello' }
某些時候咱們須要遮蔽字符串的一部分,固然不僅是對密碼作這種操做。下面代碼中經過 substr(-3)
獲得字符串的一部分,即從字符串末尾開始往前 3 個字符,而後再用你喜歡的字符填充剩餘的位置(好比說用 *
)
const password = "hackme"; password.substr(-3).padStart(password.length, "*"); // ***kme
在編碼時還須要保持代碼整潔,平時注意積累在編碼時所使到的技巧,並關注 JavaScript 的新增特性。