JavaScript ES5到ES10新特性详解
ES5 (2009) - 现代JavaScript的基石
核心特性:
严格模式
"use strict"JSON对象支持
JSON.parse()和JSON.stringify()数组方法:
forEach,map,filter,reduce,some,every对象方法:
Object.keys(),Object.create(),Object.defineProperty()
// ES5 数组方法示例var numbers = [1, 2, 3, 4, 5];var doubled = numbers.map(function(num) { return num * 2;});console.log(doubled); // [2, 4, 6, 8, 10]ES6 (2015) - 重大革新
核心特性:
let/const:块级作用域变量声明
箭头函数:() => {}
模板字符串:`Hello ${name}`
解构赋值:const {name, age} = person
类语法:class, extends, constructor
模块化:import/export
Promise:异步编程解决方案
默认参数和剩余参数
// ES6 类和解构示例class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return `Hello, I'm ${this.name}`; }}const person = new Person('Alice', 25);const {name, age} = person;ES7 (2016) - 简洁化增强
核心特性:
指数运算符:2 ** 3 // 8
Array.prototype.includes():[1,2,3].includes(2) // true
// ES7 新特性const squared = 3 ** 2; // 9const hasValue = [1, 2, 3].includes(2); // true
ES8 (2017) - 异步革命
核心特性:
async/await:异步编程终极解决方案
Object.values() 和 Object.entries()
字符串填充:padStart(), padEnd()
** trailing commas**:函数参数尾随逗号
// ES8 async/await 示例async function fetchData() { try { const response = await fetch('/api/data'); const data = await response.json(); return data; } catch (error) { console.error('Fetch failed:', error); }}// Object.entries() 示例const obj = {a: 1, b: 2};console.log(Object.entries(obj)); // [['a', 1], ['b', 2]]ES9 (2018) - 异步迭代与Rest/Spread
核心特性:
异步迭代:for await...of
Promise.finally():无论成功失败都会执行
Rest/Spread 属性:对象解构
// ES9 异步迭代async function processArray(array) { for await (let item of array) { console.log(item); }}// Promise.finally()fetch('/api/data') .then(data => console.log(data)) .catch(error => console.error(error)) .finally(() => console.log('Request completed'));ES10 (2019) - 稳定与优化
核心特性:
Array.flat() 和 Array.flatMap():数组扁平化
Object.fromEntries():键值对数组转对象
String.trimStart() 和 String.trimEnd()
可选catch绑定:try {} catch {}
// ES10 数组扁平化const nestedArray = [1, [2, [3, [4]]]];const flatArray = nestedArray.flat(2); // [1, 2, 3, [4]]// Object.fromEntries()const entries = [['name', 'Alice'], ['age', 25]];const person = Object.fromEntries(entries);
实际应用示例
以下是一个综合使用各版本特性的完整示例:
// ES6+ 综合示例class ApiService { static baseURL = 'https://api.example.com'; constructor(token) { this.token = token; } async fetchUserData(userId) { try { const response = await fetch(`${ApiService.baseURL}/users/${userId}`, { headers: { 'Authorization': `Bearer ${this.token}` } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const userData = await response.json(); const {name, email, ...otherInfo} = userData; return { name: name?.trim() ?? 'Unknown', email: email?.toLowerCase(), ...otherInfo }; } catch (error) { console.error('Failed to fetch user:', error); return null; } }}// 使用示例const api = new ApiService('your-token');const user = await api.fetchUserData(123);浏览器兼容性建议
生产环境建议:
使用Babel转译ES6+代码
配置合适的polyfill
考虑使用TypeScript获得更好的类型支持
这些新特性极大地提升了JavaScript的开发体验和代码质量,建议根据项目需求选择合适的特性组合使用。
