Object.keys與Object.values
阿新 • • 發佈:2022-03-17
1.Object.keys
Object.keys(obj),返回給定物件的所有可列舉屬性的鍵名或者索引值的陣列
a.給定物件為物件,返回鍵名陣列
let person = {name:"張三",age:25,address:"廈門",getName:function(){}} console.log(Object.keys(person)) // ['name', 'age', 'address', 'getName']
b.給定物件為陣列,返回索引陣列
let arr = ['ww','wx','zhangsan','lisi','wangwu'] console.log(Object.keys(arr))// ['0', '1', '2', '3', '4']
c.給定物件為字串,返回索引陣列
let str = 'dsafhlsafhas' console.log(Object.keys(str)) // ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
2.Object.values
Object.values與Object.keys相對,返回的是鍵值
a.給定物件為物件,返回鍵值陣列
let person = {name:"張三",age:25,address:"廈門",getName:function(){}} console.log(Object.values(person))// ['張三', 25, '廈門', ƒ]
c.給定物件為字串,返回索引陣列
let str = 'dsafhlsafhas' console.log(Object.values(str)) // ['d', 's', 'a', 'f', 'h', 'l', 's', 'a', 'f', 'h', 'a', 's'] 可以用 str.split('')直接實現