JAVASCRIPT筆記 - Object
Object,Python上應該是dictionary跟它比較類似,或是Hash table
通常會包含key跟value,key不能重複,value則無規定
value可為string或number
寫法
let obj1 = {
name: "Jack",
gender: "Male",
birthday: "1992/3/4"
}
let group = [
{ name: "Jack", gender: "Male", birthday: "1992/3/4" },
{name: "Mary", gender: "Female", birthday: "1998/7/21" }
]
Object.value() =>輸出key對應的值
console.log(Object.values(obj1))
//"Jack", "Male" , "1992/3/4"
const obj2 = { 100: "hi", 2: "hello", 5: "bye" };
console.log(Object.values(obj2)); // ['hello', 'by', 'hi']
//key為數字時,會依照數字order回傳
Object.key() => 輸出key的值
console.log(Object.keys(obj1))
// ['name', 'gender' , 'birthday']
console.log(Object.keys(obj2))
//[ '2', '5', '100']
Object.entries() =>同時輸出key跟value
也可以用迴圈
console.log(Object.entries(obj1))
// [ ["name", "Jack"], [ "gender", "Male"] , [ "birthday", "1992/3/4"] ]
console.log(Object.keys(obj2))
//[ ['2', 'hello'] , [ '5', 'bye'], [100', hi] ]
//forEach
Object.entries(obj1).forEach(([key, value]) => {
console.log(`${key} ${value}`)
})
// "name Jack", "gender Male" , "birthday 1992/3/4"
//for...of
for (const [key, value] of Object.entries(obj1)) {
console.log(`${key} ${value}`)
}
// "name Jack", "gender Male" , "birthday 1992/3/4"
Comments