JavaScript 陣列

Posted by Adam on August 24, 2022
### 陣列處理 ```js const numbers = [1, 2, 3, 4, 5, 6]; // 流式寫法:像流水線一樣清晰 const total = numbers .filter(num => num % 2 === 0) // 步驟 1: 篩選出 [2, 4, 6] .map(num => num * 2) // 步驟 2: 變成 [4, 8, 12] .reduce((sum, num) => sum + num, 0); // 步驟 3: 加總得到 24 console.log(total); // 輸出: 24 ``` ### 扁平化 ```js const users = [ { name: 'Alice', drinks: ['coffee', 'tea'] }, { name: 'Bob', drinks: ['juice'] }, { name: 'Charlie', drinks: ['coffee', 'cola'] } ]; const processedDrinks = users // 步驟 1: 提取並扁平化成 ['coffee', 'tea', 'juice', 'coffee', 'cola'] .flatMap(user => user.drinks) // 步驟 2: 去除重複項目 .filter((drink, index, arr) => arr.indexOf(drink) === index) // 步驟 3: 轉大寫 .map(drink => drink.toUpperCase()); console.log(processedDrinks); // 輸出: [ 'COFFEE', 'TEA', 'JUICE', 'COLA' ] ``` ### forEach ```js const cart = [ { item: 'Apple', price: 30 }, { item: 'Banana', price: 50 }, { item: 'Watermelon', price: 100 } ]; // 將 forEach 作為流式寫法的終點 cart .filter(product => product.price > 40) // 篩選出 Banana 和 Watermelon .map(product => `${product.item} 的價格是 ${product.price} 元`) // 轉換字串 .forEach(message => console.log(message)); // 終點:印出結果 // 輸出: // Banana 的價格是 50 元 // Watermelon 的價格是 100 元 ```