// let示例
function letExample() {
if (true) {
let x = 10;
}
console.log(x); // 报错:x is not defined
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 输出0, 1, 2
}
}
// const示例
const PI = 3.14;
// PI = 3.1415; // 报错:Assignment to constant variable
const person = { name: 'John' };
person.name = 'Mike'; // 合法:修改对象属性
// person = {}; // 报错:Assignment to constant variable
// 箭头函数
const add = (a, b) => a + b;
// 传统函数的this问题
function Person() {
this.age = 0;
setInterval(function growUp() {
this.age++; // 这里的this指向全局对象或undefined(严格模式)
}, 1000);
}
// 使用箭头函数解决this问题
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // 这里的this指向Person实例
}, 1000);
}
// 数组方法中的箭头函数
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8]
Hello, ${name}!
;<strong>${values[i]}</strong>
;
}
});
return result;
}const name = 'John';
const age = 30;
const output = highlight${name} is ${age} years old.
;
// 输出: John is <strong>30</strong> years old.
// 基本用法
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
// 剩余元素
const [first, ...rest] = [1, 2, 3, 4];
console.log(rest); // [2, 3, 4]
// 默认值
const [x = 10, y = 20] = [5];
console.log(x); // 5
console.log(y); // 20
// 基本用法
const { name, age } = { name: 'John', age: 30 };
console.log(name); // John
console.log(age); // 30
// 重命名
const { name: userName, age: userAge } = { name: 'John', age: 30 };
console.log(userName); // John
// 嵌套对象
const person = {
name: 'John',
address: {
city: 'New York',
country: 'USA'
}
};
const { address: { city } } = person;
console.log(city); // New York
// 基本用法
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet('John')); // Hello, John!
// 表达式作为默认值
function calculateTotal(price, tax = price * 0.1) {
return price + tax;
}
console.log(calculateTotal(100)); // 110
// 数组拷贝
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]
// 数组合并
const arr3 = [4, 5];
const merged = [...arr1, ...arr3];
console.log(merged); // [1, 2, 3, 4, 5]
// 函数参数展开
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
// 对象拷贝
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1 };
console.log(obj2); // { a: 1, b: 2 }
// 对象合并
const obj3 = { c: 3 };
const mergedObj = { ...obj1, ...obj3 };
console.log(mergedObj); // { a: 1, b: 2, c: 3 }
// 覆盖属性
const obj4 = { a: 10, d: 4 };
const mergedWithOverride = { ...obj1, ...obj4 };
console.log(mergedWithOverride); // { a: 10, b: 2, d: 4 }
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I'm ${this.age} years old.`;
}
static info() {
return 'This is a Person class.';
}
}
const person = new Person('John', 30);
console.log(person.greet()); // Hello, my name is John and I'm 30 years old.
console.log(Person.info()); // This is a Person class.
class Employee extends Person {
constructor(name, age, position) {
super(name, age);
this.position = position;
}
introduce() {
return `${super.greet()} I'm a ${this.position}.`;
}
}
const employee = new Employee('Mike', 25, 'Developer');
console.log(employee.introduce()); // Hello, my name is Mike and I'm 25 years old. I'm a Developer.
// Promise基本用法
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { name: 'John', age: 30 };
// resolve(data); // 成功情况
reject(new Error('Failed to fetch data')); // 失败情况
}, 1000);
});
}
// 使用Promise
fetchData()
.then(data => {
console.log('Data:', data);
return data.age;
})
.then(age => {
console.log('Age:', age);
})
.catch(error => {
console.error('Error:', error.message);
})
.finally(() => {
console.log('Finally');
});
// 并行执行多个Promise
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then(values => {
console.log('All results:', values); // [1, 2, 3]
});
// utils.js
export const PI = 3.14;
export function calculateCircleArea(radius) {
return PI * radius * radius;
}
export class Calculator {
add(a, b) {
return a + b;
}
}
// 或统一导出
const name = 'Utils';
const version = '1.0.0';
export { name, version };
// main.js
import { PI, calculateCircleArea, Calculator } from './utils.js';
console.log(PI); // 3.14
console.log(calculateCircleArea(5)); // 78.5
const calculator = new Calculator();
console.log(calculator.add(2, 3)); // 5
// 导入全部
import * as utils from './utils.js';
console.log(utils.PI); // 3.14
// 默认导出
// math.js
export default function add(a, b) {
return a + b;
}
// 使用默认导出
import add from './math.js';
console.log(add(1, 2)); // 3
const promises = [
Promise.resolve(1),
Promise.reject(new Error('Error')),
Promise.resolve(3)
];
Promise.allSettled(promises)
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Fulfilled:', result.value);
} else {
console.log('Rejected:', result.reason);
}
});
});
const regex = /\b(apple|banana|cherry)\b/g;
const text = 'I like apples and bananas.';
const matches = text.matchAll(regex);
for (const match of matches) {
console.log(match[0]); // 输出 "apple" 和 "banana"
}
const person = {
name: 'John',
address: {
city: 'New York'
}
};
// 传统写法
const zipCode = person.address && person.address.zipCode;
// 可选链写法
const zipCode = person.address?.zipCode;
const value = null;
const defaultValue = 'Default';
// 使用空值合并操作符
const result = value ?? defaultValue; // 'Default'
// 与逻辑或操作符对比
const resultOr = value || defaultValue; // 'Default'
const value2 = 0;
const result2 = value2 ?? 'Default'; // 0
const result2Or = value2 || 'Default'; // 'Default'
ES6引入了众多重要特性,显著提升了JavaScript的语言表达能力和开发效率。主要包括:
这些特性已成为现代JavaScript开发的基础,广泛应用于各类项目中。掌握ES6特性是成为一名优秀前端开发者的必备技能。
ES6 新增特性,JavaScript 新特性,ES6 语法详解,ES6 变量声明,ES6 函数增强,ES6 数组方法,ES6 对象扩展,ES6 字符串模板,ES6 模块系统,ES6 类与继承,ES6 Promise,ES6 迭代器,ES6 生成器,长尾关键词挖掘,长尾关键词优化
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。