宣告空物件const user = {} or let user = ""
排序第一個為 0 開始起算, 0, 1, 2, 3...
例如:
animal = ['dog','cat','bird' ]
console.log(animal[0])
// dog
例如: 若要取代上面排序2 的 bird, 改成rabbit
animal = ['dog','cat','bird' ]
animal[2] = 'rabbit'
console.log(animal[2])
// rabbit
animal[3] = 'cow'
console.log(animal)
// ['dog','cat','rabbit','cow' ]
obj['key'] = 'value'
//括號記法(bracket notation)
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
(來源取自於Alpha Camp 2-1學習課程圖片)
let nums = [0,1,2,3,4]
nums.push(5)
console.log(nums)
//[0,1,2,3,4,5]
nums.pop()
console.log(nums)
//[0,1,2,3,4]
nums.shift()
console.log(nums)
//[1,2,3,4]
nums.unshift(0.5)
console.log(nums)
//[0.5,1,2,3,4]
(來源取自於Alpha Camp 2-1學習課程圖片)
let nums = [0,1,2,3,4]
nums.splice(2,0,99)
//[0,1,99,2,3,4]
此三個參數分別為:
splice()會改變原有的nums陣列,但若使用相似的slice(),可以取出陣列數值,但不改變原有陣列
slice() 方法會回傳一個新的陣列物件,為原陣列選擇從"開始"至"結束"(不含結束位置的數值)的淺拷貝(shallow copy)
arr.slice([begin[, end]])
const animals = ['dog','cat','rabbit','cow','sheep','lion']
console.log(animals.slice(2))
// 從第二個位置起開始出現至最後一個數值 (因為沒有結束的位置)
console.log(animals.slice(2,5))
//['rabbit','cow','sheep']
console.log(animals.slice(2,-1))
//可使用負數索引,表示由陣列的最末項開始提取。slice(2,-1) 代表拷貝陣列中第三個元素至倒數第二個元素。
//['rabbit','cow','sheep']
console.log(animals.slice(-2))
//slice(-2) 代表拷貝陣列中的最後兩個元素。假如 begin 為 undefined,則 slice 會從索引 0 開始提取。['sheep','lion']
console.log(animals.slice(-1))
//['lion']
concat (不會改變原有陣列) vs push (新增數值至陣列,原有陣列被改變)
array.concat
// 回傳新的陣列
let daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
let newDaysOfWeek = daysOfWeek.concat(['Saturday', 'Sunday'])
console.log(daysOfWeek) // ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
console.log(newDaysOfWeek) // ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
array.push
// 直接修改原本陣列
let daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
daysOfWeek.push('Saturday', 'Sunday')
console.log(daysOfWeek) // ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
筆記學習資源: Alpha Camp, W3School