自從知道了這幾個 JavaScript 技巧,下班都變早了!
誰要是說 JavaScript 是世界上比較好的語言,估計會被唾沫星子淹沒。但是如果說 JavaScript 是世界上應(yīng)用很廣泛的編程語言,估計大部分人都沒意見。尤其是有了 NodeJS 之后,JavaScript 更是無孔不入。
Atwood 定律:“任何可以使用 JavaScript 來編寫的應(yīng)用,最終會由 JavaScript 編寫。”
即便如此,JavaScript 還是有一些鮮為人知的特性和技巧,不太常見,但是非常有用。本文不打算介紹那些稀奇古怪的特性,因為除了作為茶余飯后的談資,沒什么卵用實際用途。本文要介紹的這 5 個技巧,學(xué)完即用,用完即走(下班)!
1.加號操作符+
確定沒搞錯?我小學(xué)一年級的侄子都知道啊!沒錯,基本的算術(shù)運算符+你肯定知道:
- const two = 1 + 1;
但這里說的不是數(shù)字相加,而是將將表達(dá)式轉(zhuǎn)換成數(shù)字的操作符。
- console.log(+new Date()); // 1592102280555
- console.log(+true); // 1
- console.log(+false); // 0
- const random = {
- valueOf: () => Math.floor(Math.random() * 100),
- };
- console.log(+random); // 4
- console.log(+random); // 26
- console.log(+random); // 47
剛接觸 JavaScript 的新手可能覺得這種寫法有點奇怪,數(shù)字類型轉(zhuǎn)換會傾向于用Number()函數(shù)。結(jié)果是一樣的,但是用+不是簡潔多了?另外值得說明的是,如果對象上包含valueOf方法,+操作符會返回這個方法的結(jié)果。比如上面的例子。
2.debugger 語句
在瀏覽器 DevTools 上打斷點調(diào)試,基本上人人都會。但是你知道怎么在代碼里標(biāo)記斷點嗎?沒錯,就是用debugger語句。當(dāng)你想快速斷點到某個指定代碼位置時,這個技巧就比較方便了。
- const bubbleSort = (arr) => {
- const length = arr.length;
- for (let i = 0; i < length; i++) {
- for (let j = 0; j < length - i - 1; j++) {
- if (arr[j] > arr[j + 1]) {
- debugger;
- [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
- }
- }
- }
- return arr;
- };
- console.log(bubbleSort([8, 2, 19, 8, 4, 5, 2])); // 2, 2, 4, 5, 8, 8, 19
debugger
3.逗號操作符
逗號?我看你是逗我吧!真沒逗你,這里說的逗號不是數(shù)組里的逗號,或者對象屬性之間的逗號,而是表達(dá)式里的逗號操作符。比如const a = (1, 2),a的值就是 2。逗號操作符讓多個表達(dá)式按順序執(zhí)行,并返回最后一個表達(dá)式的值。這有什么用呢?可以讓代碼更簡潔。比如:
- let money = 10;
- const hasStudied = false;
- const relax = () => console.log('relax');
- const study = () => console.log('study');
- // 既完成變量賦值,又執(zhí)行了方法
- hasStudied ? (money++, relax()) : ((money /= 2), study());
- console.log(money); // study 5
- // 批量定義多個變量
- for (let i = 1, j = 2; i + j < 10; i++, j++) {
- console.log(i, j);
- }
- // 1 2; 2 3; 3 4; 4 5;
- // 不改變現(xiàn)有方法實現(xiàn)的情況下,增加邏輯
- <button @click="visible = false, onConfirm()">確 定<button>
4.集合對象 Set
這是 ES6 引入的數(shù)據(jù)結(jié)構(gòu),集合類型 Set。學(xué)過數(shù)學(xué)的都知道,集合的特性是不包含重復(fù)元素。有一道很常見的面試題,就是數(shù)組去重問題。當(dāng)然,面試題的本意可能不是讓你直接用 Set,而是自己實現(xiàn)去重的邏輯。但是在實際工作中用來去重,它不香嗎?還可以用來計算兩個集合的交集:
- // 數(shù)組去重
- const arr = [1, 1, 7, 5, 6, 6, 6, 8, 7];
- // 傳統(tǒng)方式
- let noDup = arr.filter((a, b) => arr.indexOf(a) === b);
- // 用 Set 更方便
- noDup = [...new Set(arr)];
- console.log(noDup); // 1 7 5 6 8
- // 集合操作
- let a = new Set('hello world!');
- // "h", "e", "l", "o", " ", "w", "r", "d", "!"
- let b = new Set('jianshu is cool!');
- // "j", "i", "a", "n", "s", "h", "u", " ", "c", "o", "l", "!"
- // 交集
- const intersection = (a, b) => {
- let intersection = new Set();
- for (let elem of b) {
- if (a.has(elem)) {
- intersection.add(elem);
- }
- }
- return intersection;
- };
- console.log(intersection(a, b));
- // "h", " ", "o", "l", "!"
5.原生 Date 操作
我碰到很多前端開發(fā),凡是日期操作必用 moment.js 之類的庫。不是說不能用,但是如果只是少數(shù)地方用了少數(shù)幾個 API,比如簡單的格式化,有必要引入一個庫嗎?再說了,如果碰到一些自定義需求,API 不支持怎么辦?其實原生操作并沒有你想象的那么麻煩,了解原理和邏輯后很快就可以自己寫一個。比如格式化:
- function formatDate(date, format) {
- var calendar = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
- format = format || 'Y-m-d';
- var dateObj = new Date(date);
- if(isNaN(+dateObj)) {
- return 'Invalid Date';
- }
- var year = dateObj.getFullYear(),
- month = dateObj.getMonth() + 1,
- date = dateObj.getDate();
- return format.replace('Y', year).replace('m', month).replace('d', date).replace('M', calendar[month - 1]);
- }
也就幾行代碼的事!再比如,獲取上個月的最后一天,可能 moment.js 有相關(guān)的 API,我也懶得去查了,原生也很簡單:
- const day1 = new Date();
- day1.setDate(-1); // 難以置信,就這么簡單!
總結(jié)
沒啥好總結(jié)的,干就完了!