JavaScript ES5到ES10新特性详解

ES5 (2009) - 现代JavaScript的基石

核心特性:

  • 严格模式 "use strict"

  • JSON对象支持 JSON.parse() 和 JSON.stringify()

  • 数组方法:forEachmapfilterreducesomeevery

  • 对象方法: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的开发体验和代码质量,建议根据项目需求选择合适的特性组合使用。


标签:

相关文章

php mvc架构的简单例子

以下是一个简单的 PHP MVC 架构示例,包含基本的模型(Model)、视图(View)和控制器(Controller)结构:目录结构project/├── app/│   ├─...

RESTful API

RESTful API 是一种基于 HTTP 协议的应用程序接口设计风格,其核心思想是将网络中的资源抽象为 URL,通过标准 HTTP 方法对资源进行操作‌。以下是其关键特性和设计原则:一、核心设计理...

php 消息队列例子

‌RabbitMQ方案‌安装扩展:需先安装amqp扩展,通过pecl或源码编译安装‌生产者示例:$connection = new AMQPConnection([...

Vue3 的生命周期钩子

Vue3 的生命周期钩子函数是组件从创建到销毁过程中各个阶段的关键节点,以下是主要特点和使用方式:一、核心生命周期钩子(Composition API)setup()替代了 Vue2 的 before...

前端知识

一、HTML/CSS核心‌盒模型与布局‌标准盒模型(content-box)与怪异盒模型(border-box)的区别及box-sizing的作用Flex布局实现三栏等高布局(flex-grow分配剩...

gibbon

n. [脊椎] 长臂猿\nn. (Gibbon)人名;(英、葡、匈、塞、巴基)吉本gibbon 长臂猿词源不详,由18世纪法国驻印度总督将该词引进印度。来自可能常用名Gilbert的昵称。gibbon...