1舞终、 帶有多個(gè)條件的 if 語(yǔ)句
把多個(gè)值放在一個(gè)數(shù)組中穴店,然后調(diào)用數(shù)組的 includes 方法。
//longhand
if(x ==='abc'|| x ==='def'|| x ==='ghi'|| x ==='jkl') {//logic}
//shorthand
if(['abc','def','ghi','jkl'].includes(x)) {//logic}
2、簡(jiǎn)化 if true...else
對(duì)于不包含大邏輯的 if-else 條件衔憨,可以使用下面的快捷寫(xiě)法。我們可以簡(jiǎn)單地使用三元運(yùn)算符來(lái)實(shí)現(xiàn)這種簡(jiǎn)化袄膏。
// Longhand
let test: boolean;
if(x > 100) {test=true;}else{test=false;}
// Shorthand
let test= (x > 10) ?true:false;//或者我們也可以直接用let test= x > 10;console.log(test);
如果有嵌套的條件践图,可以這么做。
let x =300,
test2 = (x >100) ?'greater than 100': (x <50) ?'less 50':'between 50 and 100';
console.log(test2);// "greater than 100"
3沉馆、聲明變量
當(dāng)我們想要聲明兩個(gè)具有相同的值或相同類(lèi)型的變量時(shí)码党,可以使用這種簡(jiǎn)寫(xiě)。
//Longhand?
let test1;
let test2 =1;
//Shorthand?
let test1, test2 =1;
4斥黑、null揖盘、undefined 和空值檢查
當(dāng)我們創(chuàng)建了新變量,有時(shí)候想要檢查引用的變量是不是為非 null 或 undefined心赶。
JavaScript 確實(shí)有一個(gè)很好的快捷方式來(lái)實(shí)現(xiàn)這種檢查扣讼。
// Longhand
if(test1 !==null|| test1 !==undefined|| test1 !=='') {let test2 = test1;}
// Shorthand
let test2 = test1 ||'';
5缺猛、?null 檢查和默認(rèn)賦值
let test1 =null,
test2 = test1 ||'';
console.log("null check", test2);// 輸出 ""
6缨叫、?undefined 檢查和默認(rèn)賦值
let test1 =undefined,
test2 = test1 ||'';
console.log("undefined check", test2);// 輸出 ""
一般值檢查
let test1 ='test',
test2 = test1 ||'';
console.log(test2);// 輸出: 'test'
另外,對(duì)于上述的 4荔燎、5耻姥、6 點(diǎn),都可以使用?? 操作符有咨。
如果左邊值為 null 或 undefined琐簇,就返回右邊的值。默認(rèn)情況下座享,它將返回左邊的值婉商。
const test=null??'default';
console.log(test);// 輸出結(jié)果: "default"
const test1 =0??2;
console.log(test1);// 輸出結(jié)果: 0
7、給多個(gè)變量賦值
當(dāng)我們想給多個(gè)不同的變量賦值時(shí)渣叛,這種技巧非常有用丈秩。
//Longhand?
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand?
let [test1, test2, test3] = [1, 2, 3];
8、簡(jiǎn)便的賦值操作符
在編程過(guò)程中淳衙,我們要處理大量的算術(shù)運(yùn)算符蘑秽。這是 JavaScript 變量賦值操作符的有用技巧之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
9箫攀、?if 判斷值是否存在
這是我們都在使用的一種常用的簡(jiǎn)便技巧肠牲,在這里仍然值得再提一下。
// Longhand
if(test1 ===true)or if(test1 !=="")or if(test1 !==null)// Shorthand //檢查空字符串靴跛、null或者undefined
if(test1)
注意:如果 test1 有值缀雳,將執(zhí)行 if 之后的邏輯,這個(gè)操作符主要用于 null 或 undefinded 檢查梢睛。
10肥印、?用于多個(gè)條件判斷的 && 操作符
如果只在變量為 true 時(shí)才調(diào)用函數(shù)严拒,可以使用 && 操作符。
//Longhand?
if(test1) { callMethod(); }?
//Shorthand?
test1 &&callMethod();
11竖独、for each 循環(huán)
這是一種常見(jiàn)的循環(huán)簡(jiǎn)化技巧裤唠。
// Longhand
for(vari =0; i < testData.length; i++)
// Shorthand
for(letiintestData) or for(letioftestData)
遍歷數(shù)組的每一個(gè)變量。
function testData(element, index, array){console.log('test['+ index +'] = '+ element);}
[11,24,32].forEach(testData);// logs: test[0] = 11, test[1] = 24, test[2] = 32
12莹痢、比較后返回
我們也可以在 return 語(yǔ)句中使用比較种蘸,它可以將 5 行代碼減少到 1 行。
// Longhand
let test;functioncheckReturn(){
if(!(test ===undefined)) {returntest;}else{returncallMe('test');? ? }}
var data = checkReturn();
console.log(data);//output test
functioncallMe(val){console.log(val);}
// Shorthand
function checkReturn(){returntest || callMe('test');}
13竞膳、?箭頭函數(shù)
//Longhand?
function add(a, b){returna + b;}?
//Shorthand?
const add =(a, b) =>a + b;
更多例子:
function callMe(name){console.log('Hello', name);}
callMe =name=>console.log('Hello', name);
14航瞭、簡(jiǎn)短的函數(shù)調(diào)用
我們可以使用三元操作符來(lái)實(shí)現(xiàn)多個(gè)函數(shù)調(diào)用。
// Longhand
function test1(){console.log('test1');};
functiontest2(){console.log('test2');};
var test3 =1;
if(test3 ==1) {? test1();}else{? test2();}
// Shorthand(test3 ===1? test1:test2)();
15坦辟、switch 簡(jiǎn)化
我們可以將條件保存在鍵值對(duì)象中刊侯,并根據(jù)條件來(lái)調(diào)用它們。
// Longhand
switch (data) {
? case 1:? ? test1();?
?break;??
case 2:? ? test2();??
break;??
case 3:? ? test();??
break;??
// ...}
// Shorthand
var data = {??
1: test1,?
2: test2,??
3: test};
data[something] && data[something]();
16锉走、隱式返回
通過(guò)使用箭頭函數(shù)滨彻,我們可以直接返回值,不需要 return 語(yǔ)句挪蹭。
//longhand
function
calculate(diameter){
return Math.PI * diameter
}
//shorthand
calculate =diameter=>(Math.PI * diameter;)
17亭饵、?指數(shù)表示法
// Longhand
for(vari =0; i <10000; i++) { ... }
// Shorthand
for(vari =0; i <1e4; i++) {
18、默認(rèn)參數(shù)值
//Longhand
function add(test1, test2){
if(test1 ===undefined)
test1 =1;
if(test2 ===undefined)
test2 =2;
return test1 + test2;
}
//shorthand
add =(test1 =1, test2 =2) =>(test1 + test2);
add()//輸出結(jié)果: 3
19梁厉、延展操作符簡(jiǎn)化
//longhand
// 使用concat連接數(shù)組
const data= [1,2,3];
const test = [4,5,6].concat(data);
//shorthand
// 連接數(shù)組
const data= [1,2,3];
consttest = [4,5,6, ...data];
console.log(test);// [ 4, 5, 6, 1, 2, 3]
我們也可以使用延展操作符進(jìn)行克隆辜羊。
//longhand
// 克隆數(shù)組
const test1 = [1,2,3];
const test2 = test1.slice()
//shorthand//克隆數(shù)組
const test1 = [1,2,3];
const test2 = [...test1];
20、模板字面量
如果你厭倦了使用 + 將多個(gè)變量連接成一個(gè)字符串词顾,那么這個(gè)簡(jiǎn)化技巧將讓你不再頭痛八秃。
//longhand
const welcome ='Hi '+ test1 +' '+ test2 +'.'
//shorthand
const welcome =`Hi${test1}${test2}`;
21、跨行字符串
當(dāng)我們?cè)诖a中處理跨行字符串時(shí)肉盹,可以這樣做昔驱。
//longhand
const data ='abc abc abc abc abc abc\n\t'+'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`
22、對(duì)象屬性賦值
let test1 ='a';
let test2 ='b';
//Longhand?
let obj = {test1: test1,test2: test2};
//Shorthand?
let obj = {test1, test2};
23垮媒、將字符串轉(zhuǎn)成數(shù)字
//Longhand?
let test1 =parseInt('123');
let test2 =parseFloat('12.3');
//Shorthand?
let test1 = +'123';
let test2 = +'12.3';
24舍悯、解構(gòu)賦值
//longhand
const test1 =this.data.test1;
const test2 =this.data.test2;
const test2 =this.data.test3;
//shorthand
const{ test1, test2, test3 } =this.data;
25、數(shù)組 find 簡(jiǎn)化
當(dāng)我們有一個(gè)對(duì)象數(shù)組睡雇,并想根據(jù)對(duì)象屬性找到特定對(duì)象萌衬,find 方法會(huì)非常有用。
const data= [{
type:'test1',name:'abc'? ??
},? ? {
type:'test2',name:'cde'? ??
},? ? {
type:'test1',name:'fgh'? ??
},]
function findtest1(name) {
for(let i =0; i data.type ==='test1'&&data.name ==='fgh');
console.log(filteredData);
// { type: 'test1', name: 'fgh' }
26它抱、條件查找簡(jiǎn)化
如果我們要基于不同的類(lèi)型調(diào)用不同的方法秕豫,可以使用多個(gè) else if 語(yǔ)句或 switch,但有沒(méi)有比這更好的簡(jiǎn)化技巧呢?
// Longhand
if(type==='test1') {??
test1();
}else if(type==='test2') {??
test2();
}elseif(type==='test3') {
test3();
}elseif(type==='test4') {??
test4();
}else{
thrownewError('Invalid value '+type);
}
// Shorthand
var types = {??
test1: test1,??
test2: test2,??
test3: test3,??
test4: test4
};
var func = types[type];
(!func) &&throw new Error('Invalid value '+type); func();
27混移、indexOf 的按位操作簡(jiǎn)化
在查找數(shù)組的某個(gè)值時(shí)祠墅,我們可以使用 indexOf() 方法。但有一種更好的方法歌径,讓我們來(lái)看一下這個(gè)例子毁嗦。
//longhand
if(arr.indexOf(item) >-1) {
// item found?
}
if(arr.indexOf(item) ===-1) {
// item not found
}
//shorthand
if(~arr.indexOf(item)) {
// item found
}
if(!~arr.indexOf(item)) {
// item not found
}
按位 ( ~ ) 運(yùn)算符將返回 true(-1 除外),反向操作只需要!~回铛。另外狗准,也可以使用 include() 函數(shù)。
if(arr.includes(item)) {//如果找到項(xiàng)目茵肃,則為true}
28腔长、Object.entries()
這個(gè)方法可以將對(duì)象轉(zhuǎn)換為對(duì)象數(shù)組。
const data= { test1:'abc', test2:'cde', test3:'efg'};
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ ['test1','abc'],['test2','cde'],['test3','efg']
]
**/
29验残、Object.values()
這也是 ES8 中引入的一個(gè)新特性捞附,它的功能類(lèi)似于 Object.entries(),只是沒(méi)有鍵您没。
const data = {test1:'abc',test2:'cde'};
const arr =Object.values(data);
console.log(arr);
/** Output:[ 'abc', 'cde']**/
30鸟召、雙重按位操作
// Longhand
Math.floor(1.9) ===1// true
// Shorthand
~~1.9===1// true
31、重復(fù)字符串多次
為了重復(fù)操作相同的字符紊婉,我們可以使用 for 循環(huán)药版,但其實(shí)還有一種簡(jiǎn)便的方法辑舷。
//longhand?
lettest='';
for(let i = 0; i < 5; i ++) {
test+='test ';
}?
console.log(str); //test test test test test
//shorthand?
'test '.repeat(5);
32喻犁、查找數(shù)組的最大值和最小值
const arr = [1,2,3];
Math.max(…arr);// 3
Math.min(…arr);// 1
33、獲取字符串的字符
let str ='abc';
//Longhand?
str.charAt(2);// c
//Shorthand?
str[2];// c
34何缓、?指數(shù)冪簡(jiǎn)化
//longhand
Math.pow(2,3);// 8
//shorthand
2**3// 8
本文完~