//[]陣列 //只有值,可包任何型別 //取值用索引,順序很重要因為要知道第幾個才能取 const colors = ["yellow", "red", "blue"]; const any = [123, true, "Tom"];//可混合 //length 長度 console.log(`colors陣列共用${colors.length}筆`); //讀取陣列,陣列從從0開始算 let myColor = colors[2]; console.log(myColor); // "blue" myColor = colors[3]; //陣列從0開始 console.log(myColor); // undefined //陣列資料應用 let colors = []; colors[0] = "blue"; colors[1] = "yellow"; colors[3] = "red"; console.log(colors);//["blue","yellow", null,"red"] console.log(`colors陣列共用${colors.length}筆`); //colors陣列共用4筆 //unshift 加入第一筆 colors.unshift("green"); console.log(colors);//["geeen","blue","yellow",null,"red"]; //push 加入最後一筆 colors.push("black"); console.log(colors);//["geeen","blue","yellow",null,"red","black"]; //pop 刪除第一筆 colors.shift(); console.log(colors);//["blue","yellow",null,"red","black"]; //pop 刪除最後一筆 colors.pop(); console.log(colors);//["blue","yellow",null,"red"]; //splice 刪除指定資料 //splice(1 , 2) splice(起始位置(陣列從0開始) , 2(往後刪除幾筆)) colors.splice(1, 2); console.log(colors);//["blue","red"]; //splice 插入指定資料 第二參數為0 colors.splice(1, 0, "gold"); console.log(colors);//["blue","gold","red"]; //splice 修改指定資料 第二參數為1 colors.splice(1, 1, "white"); console.log(colors);//["blue","white","red"]; //forEach() 不會回傳值,主要用於執行側邊效果(side effects),例如:修改外部變數、顯示資訊或呼叫其他函式。 const arr1 = []; data.forEach(x => { arr1.push(x == "🌕" ? x = "🌕 + 🥮" : x); }); //map() 方法會建立一個新的陣列,其內容為原陣列的每一個元素經由回呼函式運算後所回傳的結果之集合。 const arr2 = data.map(x => x == "🌕" ? x = "🌕 + 🥮" : x ); //reduce() 方法將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。 const sumOfValues = data.reduce((accumulator, item) => { return accumulator + item.normalDayPrice; }, 0); //'0' 是累加器的初始值 //sort() 排序 //reverse() 反排序 //join() 變字串 //indexOf() 取索引值由前 //lastIndexOf() 取索引值由後 //some() 一個值符合條件回傳true //every() 陣列完全符合條件true //filter() 過濾 //slice() 淺拷貝至新物件 //concat() 合併2.物件 (物件型別)
//物件{} //屬性:值 //取值用屬性,順序不重要只要知道屬性就能取值 const family = { myFather: "David",//屬性 : 值 myMonther: "Mary",//屬性 : 值 dogs: 3 }; console.log(family.myFather); //讀取物件中屬性 //物件資料應用 let home = {}; //新增、修改 //點記法 (Dot notation) home.myMonther = "May"; home.myFahter = "Kevin"; home.cats = 4; console.log(home); //{"myMonther": "May","myFahter": "Kevin", "cats": 4} home.cats += 1; home.myMonther = "Tom"; console.log(home); //{"myMonther": "Tom","myFahter": "Kevin", "cats": 5} //刪除 delete home.cats; console.log(home); //{"myMonther": "Tom","myFahter": "Kevin"} console.log(home.cats); //undefined //讀取方式 //括弧記法 (Bracket notation),屬性特殊字元時必須使用 let f = "001";//特殊開頭為數字時 home[f] = "1234" console.log(home[f]);//"Kevin"3.JSON(Javascript Object Notaion)(JS物件表示法)
1.屬性都是字串 "data" : [] ; 2.沒辦法放函式 3.不能註解 4.最後一個值後面不能加入逗號參考資料
JS直播班 - 上課白板
第三堂:物件跟陣列資料處理之術