Object.keys()的详解和用法
作者:互联网
一、语法
Object.keys(obj)
参数:要返回其枚举自身属性的对象
返回值:一个表示给定对象的所有可枚举属性的字符串数组
在实际开发中,我们有时需要知道对象的所有属性;
ES5 引入了Object.keys方法,成员是参数对象自身的(不含继承的)所有可遍历( enumerable )属性的键名。
二、处理对象,返回可枚举的属性数组
let person = {name:"张三",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 = "12345字符串" Object.keys(str) // ["0", "1", "2", "3", "4", "5", "6", "7"]
五、常用技巧
1.Object.keys(obj).map( ()=>{} )
let person = {name:"张三",age:25,address:"深圳"} var newarr = Object.keys(person).map((key)=>{ return person[key] }) console.log(newarr);
2.Object.keys(obj).forEach( ()=>{} )
let person = {name:"张三",age:25,address:"深圳"} var arr = [] Object.keys(person).forEach((key)=>{ arr.push(person[key]) }) console.log(arr);
let person = {name:"张三",age:25,address:"深圳"} var arr = [] Object.keys(person).forEach((key)=>{ arr.push(key) }) console.log(arr);
六、Object.values()
Object.values()和Object.keys()是相反的操作
Object.values: 返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历( enumerable )属性的键值。
let person = {name:"张三",age:25,address:"深圳"} var obj = Object.values(person) console.log(obj);
七、Object.entries()
Object.entries:返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历( enumerable )属性的键值对数组。
let person = {name:"张三",age:25,address:"深圳"} var obj = Object.entries(person) console.log(obj);
参考---https://blog.csdn.net/wangxinxin1992816/article/details/124523086
标签:arr,keys,Object,person,详解,let,address 来源: https://www.cnblogs.com/pwindy/p/16575570.html