电子书

aow054 / 2024-09-27 / 原文

es6 (ecmascript 2015) 为 javascript 引入了多项新功能和语法改进。以下是最重要的 es6 语法的总结和示例: 1. let 和 const 关键字es6 为块作用域变量引入了 let 和 const。let:块范围变量,可以更新,但不能在同一范围内重新声明。const:块作用域常量,无法更新或重新声明。// let examplelet age = 25;age = 30; // allowed// const exampleconst name = 'john';name = 'doe'; // error: assignment to constant variable登录后复制 2. 箭头函数(=>)箭头函数为编写函数提供了更短的语法,并且不绑定自己的 this。// regular functionfunction add(a, b) { return a + b;}// arrow functionconst add = (a, b) => a + b; // implicit return登录后复制 3. 模板文字模板文字允许使用反引号 (`) 嵌入表达式和多行字符串。const name = 'alice';const greeting = `hello, ${name}!`; // string interpolationconsole.log(greeting); // hello, alice!登录后复制 4. 解构赋值解构允许您将数组中的值或对象中的属性解压到不同的变量中。数组解构:const numbers = [1, 2, 3];const [first, second] = numbers;console.log(first); // 1console.log(second); // 2登录后复制对象解构:const person = { name: 'john', age: 25 };const { name, age } = person;console.log(name); // johnconsole.log(age); // 25登录后复制 5. 默认参数函数可以有默认参数值。const greet = (name = 'guest') => `hello, ${name}!`;console.log(greet()); // hello, guest!console.log(greet('alice')); // hello, alice!登录后复制 6. 其余参数 (...)剩余运算符 (...) 允许函数接受不定数量的参数作为数组。const sum = (...numbers) => numbers.reduce((acc, num) => acc + num, 0);console.log(sum(1, 2, 3, 4)); // 10登录后复制 7. 扩展运算符 (...)扩展运算符 (...) 允许将可迭代对象(例如数组、字符串)扩展为单个元素。const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const combined = [...arr1, ...arr2];console.log(combined); // [1, 2, 3, 4, 5, 6]登录后复制 8. 课程es6 引入了类语法来定义构造函数和方法。class person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`hello, my name is ${this.name}.`); }}const john = new person('john', 25);john.greet(); // hello, my name is john.登录后复制 9. 模块(导出和导入)es6 为具有导出和导入功能的模块提供原生支持。导出:// file: math.jsexport const add = (a, b) => a + b;export const subtract = (a, b) => a - b;登录后复制导入:// file: app.jsimport { add, subtract } from './math';console.log(add(2, 3)); // 5登录后复制 10. 承诺promise 代表异步操作的最终完成(或失败)。const fetchdata = () => { return new promise((resolve, reject) => { settimeout(() => { resolve('data received'); }, 2000); });};fetchdata().then(data => console.log(data)); // data received (after 2 seconds)登录后复制 11. for-of 循??环for-of 循??环允许您迭代可迭代对象,例如数组、字符串等const fruits = ['apple', 'banana', 'cherry'];for (const fruit of fruits) { console.log(fruit);}// apple// banana// cherry登录后复制 12. 地图和设置es6 引入了新的集合类型:map(用于键值对)和 set(用于唯一值)。地图:const map = new map();map.set('name', 'john');map.set('age', 25);console.log(map.get('name')); // john登录后复制设置:const set = new Set([1, 2, 3, 3]); // duplicates are ignoredset.add(4);console.log(set.has(3)); // trueconsole.log(set.size); // 4登录后复制这些 es6 功能显着提高了 javascript 代码的可读性、可维护性和功能性。 以上就是电子书的详细内容,更多请关注我的其它相关文章!