異步編程
JavaScript 是單線程語言,通過事件循環機制處理異步操作。任務分為兩種:
宏任務(Macrotask): script整體代碼、setTimeout(時間結束執行)、setInterval(間隔執行)、I/O、UI渲染
微任務(Microtask): Promise.then/catch/finally、process.nextTick(Node)、MutationObserver
- 執行一個宏任務(JavaScript本身的代碼會作為一個紅宏任務)
- 執行所有微任務
- 渲染頁面(如果需要)
- 執行下一個宏任務
fetch Api
網絡請求API,返回Promise對象
// 基本GET請求
fetch('https://api.example.com/data').then(response => {if (!response.ok) throw new Error('Network response was not ok');return response.json(); // 解析JSON數據}).then(data => console.log(data)).catch(error => console.error('Error:', error));// POST請求示例
fetch('https://api.example.com/data', { //第二個參數設定方法,請求頭,返回格式method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({ key: 'value' }),
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
作用
- JavaScript代碼的有序執行(整個腳本先完整執行)
- 異步回調能夠在不阻塞主線程的情況下執行
- 高優先級任務(微任務)能比低優先級任務(宏任務)更快執行
數組和對象操作
展開
// 數組展開
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]// 對象展開
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }// 函數參數展開
function sum(a, b, c) { return a + b + c; }
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6// 剩余參數
const [first, ...rest] = [1, 2, 3, 4]; // first=1, rest=[2,3,4]
const { a, ...others } = { a: 1, b: 2, c: 3 }; // a=1, others={b:2,c:3}
深拷貝淺拷貝
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original }; // 或 Object.assign({}, original)shallowCopy.b.c = 3;
console.log(original.b.c); // 3 - 也被修改了
深拷貝方法
const deepCopy1 = JSON.parse(JSON.stringify(original));
// 不能處理函數、undefined、循環引用等structuredClone(original);