ES6 部分新特性使用

箭头函数

复制代码
`// 箭头函数定义
const add = (a, b) => a + b;
console.log(add(1, 2)); // 输出3

// 箭头函数表达式
const nums = [1, 2, 3];
const sum = nums.reduce((total, num) => total + num, 0);
console.log(sum); // 输出6`

模板字符串

复制代码
``// 使用模板字符串拼接字符串
const name = 'Alice';
const age = 20;
console.log(`Name: ${name}, Age: ${age}`); // 输出 Name: Alice, Age: 20``

解构赋值

复制代码
`// 从数组中解构赋值
const [x, y] = [10, 20];
console.log(x); // 输出10
console.log(y); // 输出20

// 从对象中解构赋值
const { name, age } = { name: 'Alice', age: 20 };
console.log(name); // 输出Alice
console.log(age); // 输出20`

默认参数

复制代码
``// 设置默认参数
function greet(name = 'John') {
console.log(`Hello, ${name}`);
}
greet(); // 输出 Hello, John
greet('Alice'); // 输出 Hello, Alice``

块级作用域变量(使用letconst

复制代码
`// 使用let定义块级作用域变量
if (true) {
let x = 10;
console.log(x); // 输出10
} else {
console.log(x); // ReferenceError: x is not defined
}`

类(Class)定义(扩展了ES5的类语法)

复制代码
``class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
const person = new Person('Alice');
person.greet(); // 输出 Hello, Alice``

模块化:

复制代码
`// 导出模块
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}

// 导入模块
import { PI, area } from './math';
console.log(PI); // 输出3.14159
console.log(area(5)); // 输出78.53981633974483`

解构赋值:

复制代码
`let [x, y] = [10, 20];
console.log(x); // 输出10
console.log(y); // 输出20

let { name, age } = { name: 'Alice', age: 20 };
console.log(name); // 输出Alice
console.log(age); // 输出20`

Promise:

复制代码
`let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Success!'), 1000);
});
promise.then(result => console.log(result)); // 输出Success!(1秒后)`
相关推荐
懂懂tty几秒前
Vue2与Vue3之间API差异
前端·javascript·vue.js
Dxy123931021613 分钟前
Python线程锁:为什么多线程会“打架“,以及怎么解决
开发语言·前端·python
guygg8824 分钟前
人行走作用下板的振动响应 MATLAB 仿真
开发语言·matlab
小二·1 小时前
Next.js 15 全栈开发实战
开发语言·javascript·ecmascript
fox_lht1 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
java1234_小锋1 小时前
LangChain4j 开发Java Agent智能体- 多模态支持
java·开发语言·langchain4j
凡人叶枫1 小时前
Effective C++ 条款23:宁以 non-member、non-friend 替换 member 函数
linux·开发语言·c++·嵌入式开发
张忠琳1 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
盈建云系统1 小时前
B2B产品展示网站怎么做?从产品目录到询盘表单,企业获客页面搭建流程
开发语言·网站搭建·开发网站
不会C语言的男孩1 小时前
Linux 系统编程 · 第 4 章:文件属性与元数据
linux·c语言·开发语言