ES8中五個最具變革性的JavaScript特性
ES8包含了許多有價值的特性,徹底改變了我們編寫JavaScript的方式。
代碼變得更簡潔、更易編寫,并升級了新功能。
我們來看看這些特性,看看你是否錯過了哪些。
1.尾隨逗號
在ES8之前,尾隨逗號會導致語法錯誤!
? 之前:
const colors = [
'red',
'blue',
'green',
'yellow', // ? 不允許
];
const person = {
name: 'Tari Ibaba',
site: 'codingbeautydev.com' // ? 不行
};
但這引發了一些問題,重新排列列表會帶來麻煩:
我們還必須總是在最后一項添加逗號才能添加新項 — 這會使git差異變得混亂:
所以ES8修復了所有這些:
? 現在:
const colors = [
'red',
'blue',
'green',
'yellow', // ? yes
];
const person = {
name: 'Tari Ibaba',
site: 'codingbeautydev.com', // ? yes
};
它們帶來的好處也使得像Prettier這樣的工具在格式化后默認添加它們:
2.async/await
這就是async/await的起源!
不再需要煩人的then()嵌套:
? 之前:
wait().then(() => {
console.log('WHERE ARE YOU?! ??');
});
function wait() {
return new Promise((resolve) =>
setTimeout(resolve, 10 * 1000)
);
}
? 現在:
// ?? immediately invoked function expression (IIFE)
(async () => {
await wait();
console.log('WHERE ARE YOU?! ??');
})();
function wait() {
return new Promise((resolve) =>
setTimeout(resolve, 10 * 1000)
);
}
區別很明顯:
? 之前:
function getSuggestion() {
fetch('https://api.example/suggestion', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({}) // Pass the necessary payload here
})
.then((res) => {
return res.json();
})
.then((data) => {
const { suggestion } = data;
console.log(suggestion);
});
}
? 現在:
async function getSuggestion() {
const res = await fetch('https://api.example/suggestion');
const { suggestion } = await res.json();
console.log(suggestion);
}
10行 → 3行。
使用async/await,我們終于可以為異步代碼使用原生的 try-catch:
? ES8之前:
startWorkout();
function startWorkout() {
goToGym()
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
}
function goToGym() {
return new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
reject(new Error("I'm tired today!??"));
}
resolve("Let's go!??♂?");
});
}
? 現在:
startWorkout();
// ? async/await
async function startWorkout() {
try {
await goToGym();
} catch (err) {
console.log(err);
}
}
function goToGym() {
return new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
reject(new Error("I'm tired today!??"));
}
resolve("Let's go!??♂?");
});
}
3.強大的Object靜態方法
Object.values()
一個出色的靜態方法,可以將對象的所有值提取到一個數組中:
const person = {
name: 'Tari Ibaba',
site: 'codingbeautydev.com',
color: '??blue',
};
const arr = Object.values(person);
// ['Tari Ibaba', 'codingbeautydev.com', '??blue']
console.log(arr);
非常適合數據可視化:
const fruits = [
{
name: 'Banana',
pic: '??',
color: 'yellow',
},
{
name: 'Apple',
pic: '??',
color: 'red',
},
];
const keys = Object.keys(fruits.at(0));
const header = keys.map((key) => `| ${key} |`).join('');
const rows = fruits
.map((fruit) =>
keys.map((key) => `| ${fruit[key]} |`).join('')
).join('\n');
console.log(header + '\n' + rows);
Object.entries()
const person = {
name: 'Tari Ibaba',
site: 'codingbeautydev.com',
color: '??blue',
};
const arr = Object.entries(person);
/*
[
['name', 'Tari Ibaba'],
['site', 'codingbeautydev.com'],
['color', '??blue']
]
*/
console.log(arr);
將對象中的每個鍵值對捆綁在一起,生成一個元組列表:
非常適合使用對象的鍵和值進行數據轉換:
以ID為鍵的對象 → 對象列表:
? 之前:
const tasks = {
1: {
title: '???HIIT 30 minutes today',
complete: false,
},
2: {
name: 'Buy the backpack??',
complete: true,
},
};
const taskList = Object.keys(tasks).map((id) => ({
id,
...tasks[id],
}));
console.log(taskList);
? 現在:
// ? 更簡潔
const taskList = Object.entries(tasks).map(
([id, task]) => ({
id,
...task,
})
);
console.log(taskList);
4.原生字符串填充
2016年3月22日,流行的NPM包left-pad被創建者作為一種抗議形式下架,導致數千個軟件項目崩潰。
這讓許多人擔心我們可能過度依賴外部模塊 — 即使是像字符串填充這樣簡單的功能。
但幸運的是,ES8為JavaScript帶來了原生的字符串填充功能,即padStart和padEnd字符串方法:
const name = 'tari';
console.log(name.padStart(9, ' ')); // ' tari'
console.log(name.padEnd(10, '??')); // 'tari????????'
我們不再需要依賴另一個第三方依賴。
5. Object.getOwnPropertyDescriptors()
名字聽起來有點花哨,但很容易理解。
描述符是屬性的屬性 — 以下之一:
- value
- enumerable
- get
- set
- configurable
- enumerable
const person = {
name: 'Tari Ibaba',
color: '??color',
age: 999,
greet: () => console.log('Hey!'),
};
console.log(
Object.getOwnPropertyDescriptors(person)
);
最后的思考
總的來說,ES8對JavaScript來說是一個重大飛躍,引入了幾個已成為現代開發必不可少的特性。使你能夠編寫更簡潔、更富表現力和更清晰的代碼。