英文 | https://javascript.plainenglish.io/33-javascript-useful-shorthands-cheat-list-2021-e08b46a1a688
翻譯 | 楊小二
作為開發人員,我體驗到學習是一個持續的過程。随着每年都有新技術的出現與技術更新,我們都需要相應地進行技術更新,并且在工作和項目中進行充分利用它。
今天,我想與你分享一些我自己常用的JavaScript的技巧,它對我的工作提供了很大的幫助,同時,這些技巧會讓代碼更具有可讀性。
那麼,就讓我們開始今天的内容吧。
1、if
你是否對使用大量 if 語句感到厭煩?讓我們檢查一些可以在這裡提供幫助的選項。
//longhand
if (fruit === 'apple' || fruit === 'banana' || fruit === 'orange' || fruit ==='mango') {
//logic
}
//shorthand
if (['apple', 'banana', 'orange', 'mango'].includes(fruit)) {
//logic
}
2、 If... else 簡寫
當我們想使用 if-else 語句時,這個會對你有所幫助。當你使用 2-3 個 if.. else 時,它會降低你代碼的可讀性。
// Longhand
let mychoice: boolean;
if (money > 100) {
mychoice= true;
} else {
mychoice= false;
}
// Shorthand
let mychoice= (money > 10) ? true : false;
//or we can use directly
let mychoice= money > 10;
console.log(mychoice);
嵌套條件如下所示:
let salary = 300,
checking = (salary > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(checking); // "greater than 100"
3、變量聲明
當我們有相同類型的變量時,我們可以避免寫入兩次。
//Longhand
let data1;
let data2= 1;
//Shorthand
let data1, data2= 1;
4、檢查非空值
如果我們想檢查變量不為空怎麼辦?我們現在可以擺脫再次寫入所有條件。
// Longhand
if (data1 !== null || data1!== undefined || data1 !== '') {
let data2 = data1;
}
// Shorthand
let data2 = data1 || '';
5、配置設定預設值
let data1 = null,
data2 = test1 || '';
console.log("null check", data2); // output will be ""
6、未定義值檢查
let data1 = undefined,
data2 = data1 || '';
console.log("undefined check", data2); // output will be ""
正常值檢查
let data1 = 'data',
data2 = data1 || '';
console.log(data); // output: 'data'
(注意:我們也可以對主題 4,5 和 6使用運算符??)
7、空運算符
如果左側為空或未定義,則此運算符傳回右側值。
const data= null ?? 'data';
console.log(data);
// expected output: "data"
const data1 = 1 ?? 4;
console.log(data1);
// expected output: 1
8、指派
//Longhand
let data1, data2, data3;
data1 = 1;
data2 = 2;
data3 = 3;
//Shorthand
let [data1, data2, data3] = [1, 2, 3];
9、指派運算符
它主要在我們處理算術運算符時使用,就個人而言,我喜歡這裡的簡寫,因為它更具可讀性。
// Longhand
data1 = data1 + 1;
data2 = data2 - 1;
data3 = data3 * 30;
// Shorthand
data1++;
data2--;
data3 *= 30;
10、空檢查
最常用的操作數之一,但請確定你的值為真、非空字元串、定義的值和非空值。
// Longhand
if (data1 === true) or if (data1 !== "") or if (data1 !== null)
// Shorthand //
if (test1)
注意:如果 test1 有任何值,它将落入 if 循環之後的邏輯中,該運算符主要用于 null 或 undefined 檢查。
11、 AND(&&) 運算符
如果我們想避免少使用一個 if 語句,那麼這個技巧會很有幫助。
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
12、傳回簡寫
這将有助于避免使用大量代碼,專門傳回到基于傳回語句的調用方法。
// Longhand
let value;
function returnMe() {
if (!(value === undefined)) {
return value;
} else {
return callFunction('value');
}
}
var data = returnMe();
console.log(data); //output value
function callFunction(val) {
console.log(val);
}
// Shorthand
function returnMe() {
return value || callFunction('value');
}
13、 箭頭函數
//Longhand
function add(a, b) {
return a + b;
}
//Shorthand
const add = (a, b) => a + b;
讓我們再看一個例子。
function function(value) {
console.log('value', value);
}
function= value => console.log('value', value);
14、短函數調用
我們可以使用三元運算符來實作這些功能。
// Longhand
function data1() {
console.log('data1');
};
function data2() {
console.log('data2');
};
var data3 = 1;
if (data3 == 1) {
data1();
} else {
data2();
} //data1
// Shorthand
(data3 === 1 ? data1 : data2)(); //data1
15、Switch語句優化
如果你想優化你的 switch 語句,那麼這個可以提供幫助。
// Longhand
switch (data) {
case 1:
data1();
break;
case 2:
data2();
break;
case 3:
data();
break;
// And so on...
}
// Shorthand
var data = {
1: data1,
2: data2,
3: data
};
const val = 1
data[val]();
function data1() {
console.log("data1");
}
function data2() {
console.log("data2");
}
function data() {
console.log("data");
}
16、 隐式回報
即使不編寫 return 語句,箭頭函數也可以幫助傳回值,酷吧?
//longhand
function calculate(diameter) {
return Math.PI * diameter
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)
17、十進制指數
// Longhand
for (var i = 0; i < 100000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e5; i++) {
18、預設參數值
//Longhand
function add(data1, data2) {
if (data1 === undefined) data1 = 1;
if (data2 === undefined) data2 = 2;
return data1 + data2;
}
//shorthand
add = (data1 = 1, data2 = 2) => data1 + data2;
console.log(add()); //output: 3
19、 傳播運算符
在另一個地方建立數組引用和淺拷貝也很有用。
//longhand
// joining arrays using concat
const testdata= [1, 2, 3];
const values = [4 ,5 , 6].concat(data);
//shorthand
// joining arrays
const testdata = [1, 2, 3];
const values = [4 ,5 , 6, ...testdata];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
對于克隆,我們也可以使用擴充運算符。
//longhand
// cloning arrays
const data1 = [1, 2, 3];
const data2 = data1.slice()
//shorthand
// cloning arrays
const data1 = [1, 2, 3];
const data2 = [...data1];
20、模闆文字
如果你正在尋找以在字元串中附加多個值的技巧的話,那麼此技巧适合你。
//longhand
const literal = 'Hi ' + data1 + ' ' + data2 + '.'
//shorthand
const literal= `Hi ${data1} ${data2}`;
21、多行字元串
//longhand
const literal = 'abc abc abc abc abc abc\n\t'
+ 'val test,test test test test\n\t'
//shorthand
const literal = `abc abc abc abc abc abc
val test,test test test test`
22、對象屬性指派
let data1 = 'abcd';
let data2 = 'efgh';
//Longhand
let data = {data1: data1, data2: data2};
//Shorthand
let data = {data1, data2};
23、數字轉換
//Longhand
let test1 = parseInt('12');
let test2 = parseFloat('2.33');
//Shorthand
let test1 = +'12';
let test2 = +'2.33';
24、解構指派
//longhand
const data1 = this.data.data1;
const data2 = this.data.data2;
const data2 = this.data.data3;
//shorthand
const { data1, data2, data3 } = this.data;
25、 Array.find 方法
從數組中找到第一個比對值的方法之一。
const data = [{
type: 'data1',
name: 'abc'
},
{
type: 'data2',
name: 'cde'
},
{
type: 'data1',
name: 'fgh'
},
]
function datafinddata(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'data1' && data[i].name === name) {
return data[i];
}
}
}
//Shorthand
filteredData = data.find(data => data.type === 'data1' && data.name === 'fgh');
console.log(filteredData); // { type: 'data1', name: 'fgh' }
26、按位索引
如果我們可以将 indexof 方法與速記結合起來會怎樣?按位 indexof 方法為我們做同樣的工作。
//longhand
if (data.indexOf(item) > -1) { // item found
}
if (data.indexOf(item) === -1) { // item not found
}
//shorthand
if (~data.indexOf(item)) { // item found
}
if (!~data.indexOf(item)) { // item not found
}
我們也可以使用包含功能。
if (data.includes(item)) {
// true if the item found
}
27、 Object.entries()
此功能有助于将對象轉換為對象數組。
const data = {
data1: 'abc',
data2: 'cde',
data3: 'efg'
};
const arr = Object.entries(data);
console.log(arr);
//[
['data1', 'abc'],
['data2', 'cde'],
['data3', 'efg']
]
28、Object.values() 和 Object.keys()
疊代對象值會很有幫助。
const data = {
data1: 'abc',
data2: 'cde'
};
const arr = Object.values(data);
console.log(arr);
//[ 'abc', 'cde']
Object.keys() 有助于疊代對象中的鍵。
const data = {
data1: 'abc',
data2: 'cde'
};
const arr = Object.keys(data);
console.log(arr);
//[ 'data1', 'data2']
29、 雙位速記
(雙非按位運算符方法僅适用于 32 位整數)
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
30、多次重複一個字元串
此字元串方法有助于一次又一次地重複相同的字元串值。
//longhand
let data = '';
for (let i = 0; i < 5; i++) {
data += 'data ';
}
console.log(str); // data data data data data
//shorthand
'data '.repeat(5);
31、查找數組中的最大值和最小值
const data = [1, 4, 3];
Math.max(…data); // 4
Math.min(…data); // 1
32、從字元串中擷取字元
let str = 'test';
//Longhand
str.charAt(2); // s
//Shorthand
Note: this is only works if we know the index of matched character
str[2]; // c
33、Power 簡寫
//longhand
Math.pow(2,2); // 4
//shorthand
2**2 // 4
本文完~
學習更多技能
請點選下方公衆号