9 個(gè)功能強(qiáng)大的 JavaScript hack 技巧

來(lái)源 | https://dev.to/razgandeanu/9-extremely-powerful-JavaScript-hacks-4g3p
1、全部替換
var example = "potato potato";console.log(example.replace(/pot/, "tom"));// "tomato potato"console.log(example.replace(/pot/g, "tom"));// "tomato tomato"
2、提取唯一值
通過(guò)使用 Set 對(duì)象和展開運(yùn)算符,我們可以創(chuàng)建一個(gè)具有唯一值的新數(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)換為字符串
我們只需要使用帶空引號(hào)的串聯(lián)運(yùn)算符。
var converted_number = 5 + "";console.log(converted_number);// 5console.log(typeof converted_number);// string
4、?將字符串轉(zhuǎn)換為數(shù)字
我們需要的只是?+?運(yùn)算符。
請(qǐng)注意它僅適用于“字符串?dāng)?shù)字”。
the_string = "123";console.log(+the_string);// 123the_string = "hello";console.log(+the_string);// NaN
5、隨機(jī)排列數(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ù)組
只需使用展開運(yùn)算符。
var entries = [1, [2, 5], [6, 7], 9];var flat_entries = [].concat(...entries);// [1, 2, 5, 6, 7, 9]
7、縮短條件語(yǔ)句
讓我們來(lái)看這個(gè)例子:
if (available) {addToCart();}
通過(guò)簡(jiǎn)單地使用變量和函數(shù)來(lái)縮短它:
available && addToCart()
8、動(dòng)態(tài)屬性名
我一直以為必須先聲明一個(gè)對(duì)象,然后才能分配動(dòng)態(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);// []
本文完~

評(píng)論
圖片
表情
