9 個功能強大的 JavaScript 技巧

英文 | https://dev.to/razgandeanu/9-extremely-powerful-javascript-hacks-4g3p
譯文?|?https://www.html.cn/web/javascript/14872.html
1、全部替換
我們知道 string.replace()?函數(shù)僅替換第一次出現(xiàn)的情況。
你可以通過在正則表達(dá)式的末尾添加?/g 來替換所有出現(xiàn)的內(nèi)容。
var example = "potato potato";console.log(example.replace(/pot/, "tom"));// "tomato potato"console.log(example.replace(/pot/g, "tom"));// "tomato tomato"
2、提取唯一值
通過使用 Set 對象和展開運算符,我們可以創(chuàng)建一個具有唯一值的新數(shù)組。
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]var unique_entries = [...new Set(entries)];console.log(unique_entries);// [1, 2, 3, 4, 5, 6, 7, 8]
3、?將數(shù)字轉(zhuǎn)換為字符串
我們只需要使用帶空引號的串聯(lián)運算符。
var converted_number = 5 + "";console.log(converted_number);// 5console.log(typeof converted_number);// string
4、將字符串轉(zhuǎn)換為數(shù)字
我們需要的只是?+?運算符。
請注意它僅適用于“字符串?dāng)?shù)字”。
the_string = "123";console.log(+the_string);// 123the_string = "hello";console.log(+the_string);// NaN
5、隨機排列數(shù)組中的元素
我每天都在這樣做。
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];console.log(my_list.sort(function() {return Math.random() - 0.5}));// [4, 8, 2, 9, 1, 3, 6, 5, 7]
6、?展平二維數(shù)組
只需使用展開運算符。
var entries = [1, [2, 5], [6, 7], 9];var flat_entries = [].concat(...entries);// [1, 2, 5, 6, 7, 9]
7、?縮短條件語句
讓我們來看這個例子:
if (available) {addToCart();}
通過簡單地使用變量和函數(shù)來縮短它:
available && addToCart()
8、動態(tài)屬性名
我一直以為必須先聲明一個對象,然后才能分配動態(tài)屬性。
const dynamic = 'flavour';var item = {name: 'Coke',[]: 'Cherry'}console.log(item);// { name: "Coke", flavour: "Cherry" }
9、使用 length 調(diào)整/清空數(shù)組
我們基本上覆蓋了數(shù)組的 length 。
如果我們要調(diào)整數(shù)組的大小:
var entries = [1, 2, 3, 4, 5, 6, 7];console.log(entries.length);// 7entries.length = 4;console.log(entries.length);// 4console.log(entries);// [1, 2, 3, 4]
如果我們要清空數(shù)組:
var entries = [1, 2, 3, 4, 5, 6, 7];console.log(entries.length);// 7entries.length = 0;console.log(entries.length);// 0console.log(entries);// []
本文完~

