
es6 (ecmascript 2015) 为 javascript 引入了多项新功能和语法改进。以下是最重要的 es6 语法的总结和示例:
es6 为块作用域变量引入了 let 和 const。
// let example let age = 25; age = 30; // allowed // const example const name = 'john'; name = 'doe'; // error: assignment to constant variable
箭头函数为编写函数提供了更短的语法,并且不绑定自己的 this。
// regular function
function add(a, b) {
return a + b;
}
// arrow function
const add = (a, b) => a + b; // implicit return
模板文字允许使用反引号 (`) 嵌入表达式和多行字符串。
const name = 'alice';
const greeting = `hello, ${name}!`; // string interpolation
console.log(greeting); // hello, alice!
解构允许您将数组中的值或对象中的属性解压到不同的变量中。
const numbers = [1, 2, 3]; const [first, second] = numbers; console.log(first); // 1 console.log(second); // 2
const person = { name: 'john', age: 25 };
const { name, age } = person;
console.log(name); // john
console.log(age); // 25
函数可以有默认参数值。
const greet = (name = 'guest') => `hello, ${name}!`;
console.log(greet()); // hello, guest!
console.log(greet('alice')); // hello, alice!
剩余运算符 (...) 允许函数接受不定数量的参数作为数组。
const sum = (...numbers) => numbers.reduce((acc, num) => acc + num, 0); console.log(sum(1, 2, 3, 4)); // 10
扩展运算符 (...) 允许将可迭代对象(例如数组、字符串)扩展为单个元素。
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combined = [...arr1, ...arr2]; console.log(combined); // [1, 2, 3, 4, 5, 6]
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.
es6 为具有导出和导入功能的模块提供原生支持。
// file: math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
// file: app.js
import { add, subtract } from './math';
console.log(add(2, 3)); // 5
promise 代表异步操作的最终完成(或失败)。
const fetchdata = () => {
return new promise((resolve, reject) => {
settimeout(() => {
resolve('data received');
}, 2000);
});
};
fetchdata().then(data => console.log(data)); // data received (after 2 seconds)
for-of 循环允许您迭代可迭代对象,例如数组、字符串等
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherry
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 ignored set.add(4); console.log(set.has(3)); // true console.log(set.size); // 4
这些 es6 功能显着提高了 javascript 代码的可读性、可维护性和功能性。
以上就是电子书的详细内容,更多请关注php中文网其它相关文章!
ZLIBIRARY电子书是一个庞大的在线电子书和学术文章数据库,为用户提供免费获取各种材料。此网站自 2009 年以来一直运营,并被认为是全世界最大的电子书库之一。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号