Q 賦值問題
(A 1. push / = 2. Object.assign 3. Spread syntax (...)
。非同步問題
A setTimeout promise. then () microTask & macroTask
Q array manipulation
A reduce filter
Q CSS 位置排版
A header footer sidebar (左邊)main(右邊)
Q Functional component vs. Class component
A 寫了大概 5 點,然後再口頭解釋
---
賦值問題:
1. 使用 `push` 方法:將元素添加到陣列的末尾,並返回新陣列的長度。
```javascript
const array = [1, 2, 3];
array.push(4);
console.log(array); // [1, 2, 3, 4]
```
2. 使用 `Object.assign` 方法:將一個或多個源對象的屬性合併到目標對象中,並返回目標對象。
```javascript
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj); // { a: 1, b: 2 }
```
3. 使用展開語法(Spread syntax):將陣列或物件展開為獨立的元素或屬性。
```javascript
const array1 = [1, 2, 3];
const array2 = [...array1, 4];
console.log(array2); // [1, 2, 3, 4]
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 };
console.log(obj2); // { a: 1, b: 2 }
```
非同步問題:
1. 使用 `setTimeout` 函式創建一個定時器,延遲指定的時間後執行回調函式。
```javascript
setTimeout(() => {
console.log('Delayed action');
}, 1000);
```
2. 使用 Promise 和 `then()` 方法:創建一個 Promise 對象,表示一個異步操作,然後使用 `then()` 方法處理操作完成時的結果。
```javascript
const delay = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};
delay(1000).then(() => {
console.log('Delayed action');
});
```
3. microTask 和 macroTask:在事件循環中,microTask(微任務)具有比 macroTask(宏任務)更高的優先級,microTask 通常在 macroTask 完成後立即執行。
```javascript
console.log('Start');
setTimeout(() => {
console.log('Timeout (macroTask)');
}, 0);
Promise.resolve().then(() => {
console.log('Promise (microTask)');
});
console.log('End');
```
Q:陣列操作問題:
1. 使用 `reduce` 方法:對陣列的每個元素進行累積計算,返回最終的結果。
```javascript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15
```
2. 使用 `filter` 方法:根據指定的條件篩選陣列中的元素,返回符合條件
的元素組成的新陣列。
```javascript
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
```
CSS 位置排版:
在典型的網頁排版中,可以使用以下元素來實現基本的排版結構:
- `<header>`:網頁的頂部區域,通常包含網站的標題、導航菜單等。
- `<footer>`:網頁的底部區域,通常包含版權信息、頁腳導航等。
- `<sidebar>`:網頁的側邊欄區域,通常用於顯示附加內容或功能。
- `<main>`:網頁的主要內容區域,通常包含主要的內容和功能。
這些元素可以使用 CSS 的定位屬性(如 `position`、`top`、`bottom`、`left`、`right`)來進行位置排版,以實現所需的布局效果。
Functional component vs. Class component:
在 React 中,有兩種主要的組件類型:Functional Component(函數式組件)和 Class Component(類組件)。
Functional Component 是一個純函數,接收一個 props 對象作為輸入,並返回一個描述 UI 的 React 元素。它沒有內部狀態(state),只依賴於外部傳遞的 props。Functional Component 簡潔、輕量且易於測試,通常用於表示靜態的、沒有內部狀態管理需求的 UI 組件。
Class Component 則是一個 ES6 類,通過繼承 React.Component 類來定義。它可以擁有內部狀態(state)並實現生命週期方法(如 `componentDidMount`、`render` 等)。Class Component 提供了更多的功能和彈性,可以處理複雜的邏輯和狀態管理。
通常情況下,如果組件只需要單純的渲染 UI,沒有內部狀態管理的需求,可以使用 Functional Component。如果需要內部狀態管理、生命週期方法等高級功能,則可以使用 Class Component。在 React 16.8 版本之後,引入了 Hooks,使得 Functional Component 可以擁有狀態和生命週期方法,進一步提升了 Functional Component 的功能彈性。
---
Sure! Here are examples for each situation where Promises are commonly used:
1. AJAX Requests:
```javascript
function makeAjaxRequest(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(Error(xhr.statusText));
}
};
xhr.onerror = function () {
reject(Error('Network Error'));
};
xhr.send();
});
}
// Usage:
makeAjaxRequest('https://api.example.com/data')
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
```
2. Asynchronous File Operations:
```javascript
const fs = require('fs');
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
// Usage:
readFileAsync('file.txt')
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
```
3. Timeout Operations:
```javascript
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// Usage:
console.log('Start');
delay(1000)
.then(() => {
console.log('Delayed action');
});
```
4. Chaining Multiple Asynchronous Operations:
```javascript
function asyncOperation1() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Async Operation 1');
resolve();
}, 1000);
});
}
function asyncOperation2() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Async Operation 2');
resolve();
}, 2000);
});
}
// Usage:
asyncOperation1()
.then(() => asyncOperation2())
.then(() => {
console.log('All operations completed');
})
.catch((error) => {
console.error(error);
});
```
These examples demonstrate how Promises can be used in different scenarios to handle asynchronous operations and manage the results or errors in a more structured manner.