在前端开发中,ES8(ECMAScript 2017)是常见的编程语言之一。下面将介绍20条 ES8 技巧,让你在前端开发中事半功倍。本文适合初学者,同时也包含了进阶技巧。
1. async/await
ES8 中添加了 async 和 await 关键字,旨在简化 Promise 的使用。它们可以让异步代码看起来像同步代码。
async function fetchAsync () {
let response = await fetch('https://api.github.com');
let data = await response.json();
return data;
}2. Object.entries
Object.entries() 方法可以返回一个对象的键值对数组。
const person = {
name: 'John',
age: 30,
gender: 'male',
location: 'USA'
};
console.log(Object.entries(person));3. Object.values
Object.values() 方法可以返回一个对象属性的值数组。
const person = {
name: 'John',
age: 30,
gender: 'male',
location: 'USA'
};
console.log(Object.values(person));4. Array.prototype.includes
Array.prototype.includes() 方法可以判断一个数组是否包含某个元素。
const arr = [1, 2, 3]; console.log(arr.includes(2)); // true
5. String.prototype.padStart 和 String.prototype.padEnd
String.prototype.padStart 和 String.prototype.padEnd 方法可以为一个字符串添加指定的字符到指定的长度。默认情况下,它在前面或后面添加空格。
console.log('5'.padStart(2, '0')); // 05
console.log('5'.padEnd(2, '0')); // 506. Array.prototype.flat
Array.prototype.flat() 方法可以将嵌套数组转换为一维数组。
const arr = [1, 2, , [3, 4, [5, 6]]]; console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]]
7. Array.prototype.flatMap
Array.prototype.flatMap() 方法可以将嵌套数组转换为一维数组,并在这个过程中可以使用 map 函数对数组的每个元素进行处理。
const arr = [1, 2, 3]; console.log(arr.flatMap(x => [x * 2])); // [2, 4, 6]
8. Rest 参数和展开语法
Rest 参数和展开语法可以帮助我们更轻松地处理函数的参数和数组。
Rest 参数语法是用三个点(...)将多个参数转换成一个数组。
function sum (...args) {
let total = 0;
for (const arg of args) {
total += arg;
}
return total;
}
console.log(sum(1, 2, 3)); // 6展开语法是用三个点(...)将数组中的元素展开。
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; console.log([...arr1, ...arr2]); // [1, 2, 3, 4, 5, 6]
9. Promise.prototype.finally
Promise.prototype.finally() 方法可以在 Promise 完成后执行一些代码,无论 Promise 是成功还是失败。
fetch('https://api.github.com')
.then(response => console.log(response))
.catch(error => console.error(error))
.finally(() => console.log('fetching completed'));10. Object.getOwnPropertyDescriptors
Object.getOwnPropertyDescriptors() 方法可以返回一个对象所有自有属性的描述符。
const obj = {
name: 'John',
age: 30
};
console.log(Object.getOwnPropertyDescriptors(obj));11. Trailing commas
ES8 中允许在函数参数和数组中使用尾随逗号。虽然这并不影响代码的工作,但是它使代码更加易读和易于维护。
function sum (a, b,) {
return a + b;
}
const arr = [1, 2, 3,];12. Object.setPrototypeOf
Object.setPrototypeOf() 方法可以设置一个对象的原型。
// www.javascriptcn.com code example
const person = {
name: 'John',
age: 30
};
const profile = {
location: 'USA'
};
Object.setPrototypeOf(profile, person);
console.log(profile.name); // 'John'13. Object.values 和 Object.entries 的排序
ES8 中,Object.values() 和 Object.entries() 方法返回的数组元素顺序是按照对象属性插入顺序排序的。
const obj = {
name: 'John',
age: 30,
gender: 'male',
location: 'USA'
};
console.log(Object.values(obj)); // ['John', 30, 'male', 'USA']
console.log(Object.entries(obj)); // [['name', 'John'], ['age', 30], ['gender', 'male'], ['location', 'USA']]14. 正则表达式命名捕获组
ES8 中添加了正则表达式命名捕获组,可以让我们更容易地捕获和处理正则表达式中的分组。
const str = '2022-02-22';
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const groups = str.match(regex).groups;
console.log(groups.year); // '2022'15. 非转义的正则表达式的 s 修饰符
ES8 中添加了非转义的正则表达式的 s 修饰符,可以让点字符(.)匹配任何字符,包括换行符。
const str = 'Hello\nWorld'; console.log(/hello.world/si.test(str)); // true
16. BigInt
BigInt 是一种可以表示任意大的整数的原生 JavaScript 类型。
const largest = BigInt(Number.MAX_SAFE_INTEGER); console.log(largest + 1n); // 9007199254740992n
17. for-await-of 循环
for-await-of循环 可以用来遍历异步迭代器。
// www.javascriptcn.com code example
async function * getCount () {
let count = 0;
while (count < 3) {
yield Promise.resolve(count++);
}
}
(async function () {
for await (const number of getCount()) {
console.log(number);
}
}());18. 用 finally 块解决 Promise 的回调地狱
ES8 的 Promise.prototype.finally 方法可以用来解决回调地狱的问题。
fetch('https://api.github.com')
.then(response => console.log(response))
.catch(error => console.error(error))
.finally(() => console.log('fetching completed'));19. Object.keys 和 Object.values 的遍历顺序
ES8 中,Object.keys() 和 Object.values() 方法返回的对象属性顺序是固定的。
const obj = {
name: 'John',
age: 30,
gender: 'male',
location: 'USA'
};
console.log(Object.keys(obj)); // ['name', 'age', 'gender', 'location']
console.log(Object.values(obj)); // ['John', 30, 'male', 'USA']20. Random 方法的改进
ES8 中,Math.random() 方法被改进,现在可以通过 crypto.getRandomValues() 方法使用更安全的随机数生成器。
const crypto = window.crypto || window.msCrypto; const randomNumbers = new Uint32Array(1); crypto.getRandomValues(randomNumbers); console.log(randomNumbers[0] / (0xFFFFFFFF + 1)); // 任意只有0到1的浮点数
希望这 20 条 ES8 技巧能够帮助您提高前端开发的工作效率并拓宽知识面。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d00711e46428fe9ec86dd2