Object.keys方法之详解

Object.keys方法之详解

一、语法

      Object.keys(obj)

      参数:要返回其枚举自身属性的对象
    
      返回值:一个表示给定对象的所有可枚举属性的字符串数组
     

二、处理对象,返回可枚举的属性数组

      let person = { name: 'tom', age: 25, address: '南非',getName:function(){}}

      Object.keys(person) // ["name", "age", "address","getName"]
     

三、处理数组。返回索引值数组

      let arr = [1,2,3,4,5,6]

      Object.keys(arr) // ["0", "1", "2", "3", "4", "5"]
     

四、处理字符串,返回索引值数组

    let str = "object.obj字符串"

    Object.keys(str) // ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
  

使用案例

    //get请求
    let url = 'http://localhost:8081'
    let data = { name: 'tom', age: 25, address: '南非' };
    let dataStr = '';//拼接字符串
    Object.keys(data).forEach(key => {
      dataStr += key + '=' + data[key] + '&'
    })
    console.log(dataStr)
    if (dataStr !== '') {//拼接字符串
      dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
      url = url + '?' + dataStr;
      console.log(url)
    }      
    

五、常用技巧

    let person = {name:"张三",age:25,address:"深圳",getName:function(){}}

    Object.keys(person).map((key)=>{
  
      person[key] // 获取到属性对应的值,做一些处理
  
    })
   

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

    let strList = { name: 'tom', age: 25, address: '南非' };
    console.log(Object.values(strList))  //["tom", 25, "南非"]

你可能感兴趣的:(javascript)