关于Object.keys()和Object.values()的使用

1. 关于Object.keys()

1) 处理对象,返回可枚举的所有可枚举属性的字符串数组

let person ={ name:'张三',age:25,address:'深圳' }
Object.keys(person) // ['name', 'age', 'address']
Object.keys(person).forEach(key => {
  console.log(key)  //name, age, address
  console.log(person[key])  //张三, 25, 深圳
})

2)处理数组,返回索引值数组

let person =[0,2,4,6,8]
Object.keys(person) // ['0', '1', '2', '3', '4']
Object.keys(person).forEach(key => {
  console.log(key)  // 0, 1, 2, 3, 4
  console.log(person[key])  // 0,2,4,6,8
})

3) 处理字符串,返回索引值数组

let person ='abcde'
Object.keys(person) // ['0', '1', '2', '3', '4']
Object.keys(person).forEach(key => {
  console.log(key)  // 0, 1, 2, 3, 4
  console.log(person[key])  //a,b,c,d,e
})

2. 关于Object.values()

Object.values()和Object.keys()是相反的操作,把一个对象的转换为数组

let person ={ name:'张三',age:25,address:'深圳' }
Object.values(person)  //['张三', 25, '深圳']

3. 项目中常用技巧

 let person = { name: '张三', age: 25, address: 'z深圳', getName: function () {} }
 console.log(Object.keys(person)) // ['name', 'age', 'address', 'getName']
 Object.keys(person).map((key) => {
    console.log(person[key], '属性值') //获取到属性对应的值,根据需求做一些处理
  })

4. Object.keys()和Object.values() 区别

Object.keys()取对象属性名转成数组
Object.values()取对象属性值转成数组

你可能感兴趣的:(JavaScript,javascript,前端,vue.js)