# JavaScript陣列處理必學技巧 ###### tags: `JavaScript` 2022.2.25 參考教學影片網址:https://www.youtube.com/watch?v=_vFuDQ_6Xt8 ## 重點整理 #### 1. 一般寫法 V.S 箭頭字號,Function差異 (以ForEach為例) * 一般寫法 ``` arr.forEach(function(obj,key){ document.write(`單行陣列數據:${obj},此列索引值:${key}<br>`); }); ``` * 箭頭字號 ``` arr.forEach((obj,key)=>( document.write(`單行陣列數據:${obj},此列索引值:${key}<br>`) )); ``` #### 2. 樣板字面字 &emsp;&emsp;與一般「""」、「''」,差異在於「‵ ‵」可以不透過連接符號一次性將文字與變數結合呈現。 &emsp;&emsp;**打法**:單擊,鍵盤左上「~巷」按鍵。 ``` const index = 0 document.write(index +' 王'+'小'+'明<br>'); document.write(`${index} 王小明<br>`); ``` &emsp;&emsp;結果 &emsp;&emsp;![](https://i.imgur.com/ig9uolh.png) #### 3. 各類函式介紹 * ##### map:對原陣列進行額外運算,並改寫至新陣列。 ``` // 更改內容:替名字加上共同姓(王)、每人都增加一歲、呈現索引值。 const Original = [{name:'小明',age:10},{name:'小華',age:11}]; const New = Original.map((obj,key)=>({ name : `王${obj.name}`, age : obj.age+1, class:key }); console.log(Original) console.log(New) ``` &emsp;&emsp;結果 &emsp;&emsp;![](https://i.imgur.com/wsIuaHR.png) * ##### Filter:從原陣列中篩選出想要的數據,並寫至新陣列。 ``` // 篩選條件:年齡為11歲。 const Original = [{name:'小明',age:10},{name:'小華',age:11}]; const New = Original.filter((obj,key)=>( obj.age === 11 )); console.log(Orginal); console.log(New); ``` &emsp;&emsp;結果 &emsp;&emsp;![](https://i.imgur.com/ZCyUsKE.png) * ##### findIndex:找尋陣列第一個符合條件的列,匯出索引值。 ``` //搜尋條件:找尋'小明'列索引值 const Original = [{name:'小明',age:10},{name:'小華',age:11}]; const index = Original.findIndex((obj)=>(obj.name === '小明')); console.log(Original); console.log(index); ``` &emsp;&emsp;結果 &emsp;&emsp;![](https://i.imgur.com/a6wh5Eu.png) * ##### reduce:累計函數,將初始值累計後面數值。 ``` arr = [1,2,3]; console.log(arr.reduce((acc,cur)=>acc+cur,10)); //累加(初始值為:10),運行流程:10+1+2+3,結果:16。 console.log(arr.reduce((acc,cur)=>acc-cur)); //累減(初始值:1),運行流程:1-2-3,結果:-4。 console.log(arr.reduce((acc,cur)=>cur-acc)); //累減(初始值:1), 運行流程: acc=1, cur=2, 運算cur-acc:2-1=1 acc=(上步運算結果:1), cur=3, 運算cur-acc:3-1=2 結果:2。 ``` * ##### sort:排序,文字排序會依照ASCLL排序,自定義排序(如:a-b(小到大排序),排序規則: 若為「正」對換排序,若為「負或0」不變)。 ``` const test = [ {name:'Apple',score:50}, {name:'Bnanan',score:100}, {name:'1Ava',score:70}] ``` ``` //依照名字排序 console.log(test.sort((a,b)=>{ if(a.name<b.name){ return -1; } else { return 0; } })); ``` &emsp;&emsp;![](https://i.imgur.com/F5bI7sD.png) ``` //依分數排序(大到小) console.log(test.sort((a,b)=>{ return b.score-a.score })); ``` &emsp;&emsp;![](https://i.imgur.com/YomC7Eq.png) ## 教學影片範例 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> const people = [ { name:'卡斯柏', order:'鍋燒意麵', price: 80 }, { name:'小明', order:'牛肉麵', price: 120 }, { name:'漂亮阿姨', order:'滷味切盤', price: 40 }, { name:'Ray', order:'大麻醬乾麵', price: 60 }, ]; // 1. 請一一列出每個人的訂單 // 1.1 forEach // people.forEach(function(obj,key){ // console.log(obj,key); // }); // 1.2 箭頭函式 // people.forEach((obj,key)=>(console.log(obj,key))); // 2. 小明看到今天有打八折!!,請將所有訂單新增一個新價格,金額是80%。 // 2.1 forEach // const new_order = []; // people.forEach(function(obj,key){ // new_order[key] = { // ...obj, // newprice : obj.peice * 0.8 // } // }); // console.log(new_order); // 2.2 map // const new_order = people.map(function(obj,key){ // return{ // ...obj, // newprice : obj.price * 0.8 // } // }); // console.log(new_order); // 2.3 map+箭頭函式 // const newprice = people.map((obj) => ({ // ...obj, // newprice : obj.price * 0.8 // })); // console.log(newprice); // 3. 老闆說,今天疫情沒有八折啦,不過80元的可以給滷蛋。 // 3.1 forEach // const give_name = [] // people.forEach(function(obj,key){ // if(obj.peice >= 80) // { // give_name.push(obj) // } // }); // console.log(give_name) // 3.2 Filter // const give_name = people.filter(function(obj){ // return obj.price>=80 // }); // console.log(give_name); // 3.3 Filter+箭頭函式 // const give_name = people.filter((obj)=>(obj.price>=80)); // console.log(give_name); // 4. 過一段間後,老闆發現牛肉沒了,把點牛肉麵換成牛肉湯麵。 // 4.1 forEach // const NewOrder = []; // let index= -1; // people.forEach(function(obj,key){ // NewOrder[key] = {...obj} // if(obj.order==='牛肉麵') // { // index = key; // } // }); // NewOrder[index].order = '牛肉湯麵' // console.log(people) //原本訂單 // console.log(NewOrder) //更改後訂單 // 4.2 findIndex // const index = people.findIndex(function(obj,key){ // return obj.order === '牛肉麵' // }); // const NewOrder = people.map(obj=>({...obj})); //拷貝people數據,且以後對此數據更動不會改變原數據 // NewOrder[index].order = '牛肉湯麵' // console.log(people); // console.log(NewOrder); // 4.3 findIndex + 箭頭函式 // const index = people.findIndex((obj)=>(obj.order==='牛肉麵')); // const NewOrder = people.map((obj) => ({...obj})); // NewOrder[index].order = '牛肉湯麵'; // console.log(people); // console.log(NewOrder); const index = 0 // 5. 老闆說POS機壞了,麻煩幫忙出一下LI結構,方便列印發票。 // 5.1 forEach // document.write('<ul>'); // people.forEach(function(obj,key){ // document.write(`<li>${obj.name} , ${obj.order} , ${obj.price}</li>`) // }); // document.write('</ul>'); // 5.2 map+樣板字面值 // people.map(function(obj){document.write(`<li>${obj.order},${obj.price}</li>`);}); // 5.3 map+樣板字面值+箭頭函式 // people.map((obj)=>(document.write(`<li>${obj.order} , ${obj.price}</li>`);)); // 6. 老闆要收錢了,請問老闆應該收多少錢。 // 6.1 forEach // let total_price = 0; // people.forEach(function(obj,key){ // total_price += obj.price // }); // console.log(`總金額:${total_price}`) // 6.2 reduce // const totla_price =people.reduce(function(acc,cur){ // return acc+cur.price; // },0); // console.log(totla_price); // 6.3 reduce + 箭頭函式 // const totla_price = people.reduce((acc,cur)=>acc+cur.price,0); // console.log(totla_price); // 7.今天誰吃最貴!請排序所有金額。 // 7.1 sort // console.log(people.sort(function(a,b){ // return b.price-a.price; // })); // 7.2 sort + 箭頭函式 // console.log(people.sort((a,b)=>b.price-a.price)); </script> </body> </html> ```