變量聲明
ES6引入了let
和const
替代var
。let
用于聲明可變的塊級作用域變量,const
用于聲明不可變的常量。塊級作用域有效避免了變量提升和污染全局的問題。
let name = 'Alice';
const PI = 3.1415;
箭頭函數
箭頭函數簡化了函數寫法,且自動綁定當前上下文的this
值。適合用于回調函數或需要保留this
的場景。
const add = (a, b) => a + b;
array.map(item => item * 2);
模板字符串
使用反引號()包裹字符串,支持多行文本和嵌入變量。表達式通過
${}`插入。
const user = 'Bob';
console.log(`Hello ${user},
Today is ${new Date().toDateString()}`);
解構賦值
從數組或對象中提取值并賦值給變量。簡化數據提取過程,支持嵌套和默認值。
const [x, y] = [1, 2];
const {name, age} = {name: 'Tom', age: 20};
默認參數
函數參數可以設置默認值,避免手動檢查undefined
。
function greet(name = 'Guest') {return `Hello ${name}`;
}
擴展運算符
...
可用于展開數組或對象,常用于合并數據或函數傳參。
const arr1 = [1, 2];
const arr2 = [...arr1, 3]; // [1, 2, 3]
const obj = {...oldObj, newProp: 'value'};
Promise
Promise用于異步操作管理,通過then
和catch
處理成功或失敗狀態。避免了回調地獄。
fetch(url).then(response => response.json()).catch(error => console.error(error));
模塊化
ES6模塊通過import
和export
實現代碼組織。支持按需加載和靜態分析。
// module.js
export const api = 'https://example.com';
// main.js
import {api} from './module.js';
類語法
class
關鍵字提供更清晰的面向對象編程語法,包含構造函數、繼承和靜態方法。
class Person {constructor(name) {this.name = name;}greet() {return `Hello ${this.name}`;}
}
迭代器與生成器
Symbol.iterator
定義迭代協議,function*
生成器函數可暫停執行。用于自定義遍歷邏輯。
function* idGenerator() {let id = 1;while(true) yield id++;
}
const gen = idGenerator();
gen.next().value; // 1