1.交換兩個變數而沒有第三個
let x = 1;let y = 2;[x, y] = [y, x];console.log(x, y);
輸出:
2 1
2、將數字轉換為字串
const num = 1 +“”;console.log(typeof num); console.log(num);
輸出:
string1
3、將字串轉換為數字
const numStr = "124";const num = +numStr;console.log(typeof num);console.log(num);
輸出:
number 124
4、將字串拆分為陣列
要將字串拆分為陣列,可以使用擴充套件運算子(...):
const str = "Test"const strAsArr = [...str]console.log(strAsArr)
輸出:
["T", "e", "s", "t"]
5、可選連結
“可選的連結運算子(?.)允許讀取位於連線物件鏈深處的屬性的值,而不必明確驗證鏈中的每個引用是否有效。” — MDN Web文件
假設你有一個data物件,並且想要安全地訪問data.test.value。首先,你需要檢查:
data 是否被定義。
data.test 是否被定義。
在data.test.value,你可以呼叫之前,因為,你顯然無法讀取undefined屬性。
const data = {test:{value:1}}if(data && data.test){ console.log(data.test.value); }
輸出:
1
幸運的是,使用可選連結的方法,你可以簡單明瞭地編寫上面的程式碼:
const value = data?.test?.value;console.log(value)
輸出:
1
現在,你還可以安全地嘗試訪問不存在的屬性,而不會出現問題:
console.log(data?.this?.does?.not?.exist?.for?.sure)
輸出:
undefined
6、 較短的 If-Else 的空合併
這也是 if-else 的簡寫。
你可以使用看漲合併,而不是使用 if-else 構造來檢查值是否為空。該nullish合併操作 ??,如果沒有定義左側返回右側。如果是,則返回左側:
let maybeSomething;
// LONG FORM
if(maybeSomething){
console.log(maybeSomething)
} else {
console.log("Nothing found")
}
//SHORTHAND
console.log(maybeSomething ?? "Nothing found")
7、傳播解構
使用擴充套件運算子將剩餘元素分配給變數:
const student = {
name: "Matt",
age: 23,
city: "Helsinki",
state: "Finland",
};
// LONGER FORM
const name = student.name;
const age = student.age;
const address = { city: student.city, state: student.state };
// SHORTHAND
const { name, age, ...address } = student;
8、 從陣列中查詢特定元素
使用find()方法查詢匹配特定條件的元素:
const fruits = [
{ type: "Banana", color: "Yellow" },
{ type: "Apple", color: "Green" }
];
// LONGER FORM
let yellowFruit;
for (let i = 0; i < fruits.length; ++i) {
if (fruits[i].color === "Yellow") {
yellowFruit = fruits[i];
}
}
// SHORTHAND
yellowFruit = fruits.find((fruit) => fruit.color === "Yellow");
9.將物件的值收集到陣列中
用於Object.values()將物件的所有值收集到一個新陣列中:
const info = { name: "Matt", country: "Finland", age: 35 };
// LONGER FORM
let data = [];
for (let key in info) {
data.push(info[key]);
}
// SHORTHAND
const data = Object.values(info); // values值集合陣列
const data = Object.keys(info);
// key值集合陣列
10.壓縮多個條件
避免使用長|| 檢查多個條件鏈,你可以使用你剛剛在上一個技巧中學到的東西——即,使用 includes() 方法:
const num = 1;
// LONGER FORM
if(num == 1 || num == 2 || num == 3){
console.log("Yay");
}
// SHORTHAND
if([1,2,3].includes(num)){
console.log("Yay");
}
11、 指數運算子
你Math.pow()習慣把一個數字提高到一個冪嗎?你知道你也可以使用**運算子嗎?
// LONGER FORM
Math.pow(4,2); // 16
Math.pow(2,3); // 8
// SHORTHAND
4**2 // 16
2**3 // 8
12、 Math.floor() 簡寫
四捨五入Math.floor()並不是什麼新鮮事。但是你知道你也可以使用~~運算子嗎?
例如:
// LONG FORM
Math.floor(5.25) // -> 5.0
// SHORTHAND
~~5.25 // -> 5.0
13.用一行程式碼分配多個值(解構賦值)
使用解構語法在一行中分配多個值:
let num1, num2;
// LONGER FORM
num1 = 10;
num2 = 100;
// SHORTHAND
[num1, num2] = [10, 100];
這也適用於使用 JavaScript 物件:
student = {
name: "Matt",
age: 29,
};
// LONGER FORM
let name = student.name;
let age = student.age;
// SHORTHAND
let { name, age } = student;