11 個(gè) JavaScript 常用技巧

1、過濾唯一值
Set對(duì)象類型是在 ES6 中引入的,配合展開操作...一起,我們可以使用它來創(chuàng)建一個(gè)新數(shù)組,該數(shù)組只有唯一的值。const array = [1, 1, 2, 3, 5, 5, 1];const uniqueArray = [...new Set(array)];console.log(uniqueArray); // Result: [1, 2, 3, 5]
undefined,null,boolean,string和number。 (如果你有一個(gè)包含對(duì)象,函數(shù)或其他數(shù)組的數(shù)組,你需要一個(gè)不同的方法!)2、與或運(yùn)算
x > 100 ? "Above 100" : "Below 100";x?>?100???(x?>?200???"Above?200"?:?"Between?100-200")?:?"Below?100";
&&和’或’||?邏輯運(yùn)算符以更簡(jiǎn)潔的方式書寫表達(dá)式。 這通常被稱為“短路”或“短路運(yùn)算”。它是怎么工作的
&&將返回第一個(gè)條件為假的值。如果每個(gè)操作數(shù)的計(jì)算值都為true,則返回最后一個(gè)計(jì)算過的表達(dá)式。let one = 1,two = 2,three = 3;console.log(one && two && three); // Result: 3console.log(0 && null); // Result: 0
||將返回第一個(gè)條件為真的值。如果每個(gè)操作數(shù)的計(jì)算結(jié)果都為false,則返回最后一個(gè)計(jì)算過的表達(dá)式。let one = 1,two = 2,three = 3;console.log(one || two || three); // Result: 1console.log(0?||?null);?//?Result:?null
例一
if/else語句來檢查foo是可接受的類型,但是這可能會(huì)變得非常冗長(zhǎng)。或運(yùn)行可以幫助我們簡(jiǎn)化操作:return (foo || []).length;
foo是 true,它將被返回。否則,將返回空數(shù)組的長(zhǎng)度:0。例二
this.state中訪問一個(gè)名為data的屬性,但是在我們的程序成功返回一個(gè)獲取請(qǐng)求之前,data?是未定義的。this.state.data可能會(huì)阻止我們的應(yīng)用程序運(yùn)行。 為了解決這個(gè)問題,我們可以將其做進(jìn)一步的判斷:if (this.state.data) {return this.state.data;} else {return "Fetching Data";}
或'?運(yùn)算符提供了更簡(jiǎn)潔的解決方案:return?this.state.data?||?"Fetching?Data";
一個(gè)新特性: Optional Chaining
Cannot read property xxx of undefined的錯(cuò)誤。optional chaining?就是添加了?.這么個(gè)操作符,它會(huì)先判斷前面的值,如果是?null?或?undefined,就結(jié)束調(diào)用、返回?undefined。this.state.data?.()。或者,如果我們主要關(guān)注state?是否已定義,我們可以返回this.state?.data。.babelrc文件中。3、轉(zhuǎn)換為布爾值
true和false之外,JavaScript 還將所有其他值視為?‘truthy’?或‘falsy’。0,“”,null,undefined,NaN,當(dāng)然還有false,這些都是‘falsy’true和false之間切換。它也會(huì)將類型轉(zhuǎn)換為“boolean”。const isTrue = !0;const isFalse = !1;const alsoFalse = !!0;console.log(isTrue); // Result: trueconsole.log(typeof?true);?//?Result:?"boolean"
4、?轉(zhuǎn)換為字符串
+后跟一組空引號(hào)""。const val = 1 + "";console.log(val); // Result: "1"console.log(typeof?val);?//?Result:?"string"
5、轉(zhuǎn)換為數(shù)字
+可以快速實(shí)現(xiàn)相反的效果。let int = "15";int = +int;console.log(int); // Result: 15console.log(typeof int);Result:?"number";
console.log(+true); // Return: 1console.log(+false);?//?Return:?0
+將被解釋為連接操作符,而不是加法操作符。當(dāng)這種情況發(fā)生時(shí)(你希望返回一個(gè)整數(shù),而不是浮點(diǎn)數(shù)),您可以使用兩個(gè)波浪號(hào):~~。— ( — n — 1) — 1 = n + 1 — 1 = n。 換句話說,~—16?等于15。const int = ~~"15";console.log(int); // Result: 15console.log(typeof int);Result:?"number";
~true = -2和~false = -1。6、性能更好的運(yùn)算
**作為冪的簡(jiǎn)寫,這比編寫Math.pow(2, 3)?更快。 這是很簡(jiǎn)單的東西,但它之所以出現(xiàn)在列表中,是因?yàn)闆]有多少教程更新過這個(gè)操作符。console.log(2?**?3);?//?Result:?8
異或運(yùn)算符。2為基數(shù)的冪才存在簡(jiǎn)寫,使用按位左移操作符<<n);2 << (n - 1);2 ** n;
2 << 3 = 16等于2 ** 4 = 16。7、快速浮點(diǎn)數(shù)轉(zhuǎn)整數(shù)
Math.floor()、Math.ceil()或Math.round()。但是還有一種更快的方法可以使用|(位或運(yùn)算符)將浮點(diǎn)數(shù)截?cái)酁檎麛?shù)。console.log(23.9 | 0); // Result: 23console.log(-23.9 | 0); // Result: -23
|的行為取決于處理的是正數(shù)還是負(fù)數(shù),所以最好只在確定的情況下使用這個(gè)快捷方式。n為正,則n | 0有效地向下舍入。 如果n為負(fù)數(shù),則有效地向上舍入。 更準(zhǔn)確地說,此操作將刪除小數(shù)點(diǎn)后面的任何內(nèi)容,將浮點(diǎn)數(shù)截?cái)酁檎麛?shù)。~~來獲得相同的舍入效果,如上所述,實(shí)際上任何位操作符都會(huì)強(qiáng)制浮點(diǎn)數(shù)為整數(shù)。這些特殊操作之所以有效,是因?yàn)橐坏?qiáng)制為整數(shù),值就保持不變。刪除最后一個(gè)數(shù)字
按位或運(yùn)算符還可以用于從整數(shù)的末尾刪除任意數(shù)量的數(shù)字。這意味著我們不需要使用這樣的代碼來在類型之間進(jìn)行轉(zhuǎn)換。let str = "1553";Number(str.substring(0,?str.length?-?1));
console.log((1553 / 10) | 0); // Result: 155console.log((1553 / 100) | 0); // Result: 15console.log((1553?/?1000)?|?0);?//?Result:?1
8、?類中的自動(dòng)綁定
this.myMethod = this.myMethod.bind(this)import React, { Component } from React;export default class App extends Compononent {constructor(props) {super(props);this.state = {};}myMethod = () => {// This method is bound implicitly!}render() {return (<><div>{this.myMethod()}div>>)}};
9、?數(shù)組截?cái)?/span>
splice()更快的方法。length屬性,就像這樣let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];array.length = 4;console.log(array);?//?Result:?[0,?1,?2,?3]
slice()方法的運(yùn)行時(shí)更快。如果速度是你的主要目標(biāo),考慮使用:let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];array = array.slice(0, 4);console.log(array);?//?Result:?[0,?1,?2,?3]
10、獲取數(shù)組中的最后一項(xiàng)
slice()可以接受負(fù)整數(shù),如果提供它,它將接受數(shù)組末尾的值,而不是數(shù)組開頭的值。let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];console.log(array.slice(-1)); // Result: [9]console.log(array.slice(-2)); // Result: [8, 9]console.log(array.slice(-3));?//?Result:?[7,?8,?9]
11、格式化 JSON 代碼
JSON.stringify,但是您是否意識(shí)到它還可以幫助你縮進(jìn) JSON?stringify()方法有兩個(gè)可選參數(shù):一個(gè)replacer函數(shù),可用于過濾顯示的 JSON 和一個(gè)空格值。console.log(JSON.stringify({ alpha: "A", beta: "B" }, null, "\t"));// Result:// '{// "alpha": A,// "beta": B// }'

評(píng)論
圖片
表情
