let obj = { id: 1, name: ‘rosnewang‘, age: 20 } for(let key in obj){ console.log(key + ‘---‘ + obj[key]) } // id --- 1 name --- rosenwang age --- 20
二,Object.keys()和Object.values()
var obj = {‘a‘:‘123‘,‘b‘:‘345‘}; console.log(Object.keys(obj)); //[‘a‘,‘b‘] var obj1 = { 100: "a", 2: "b", 7: "c"}; console.log(Object.keys(obj1)); // console: ["2", "7", "100"] var obj2 = Object.create({}, { getFoo : { value : function () { return this.foo } } }); obj2.foo = 1; console.log(Object.keys(obj2)); // console: ["foo"]复制代码
传入字符串,返回索引
var str = ‘ab1234‘; console.log(Object.keys(obj)); //[0,1,2,3,4,5]构造函数 返回空数组或者属性名复制代码
构造函数,返回空数组或者属性名
function Pasta(name, age, gender) { this.name = name; this.age = age; this.gender = gender; this.toString = function () { return (this.name + ", " + this.age + ", " + this.gender); } } console.log(Object.keys(Pasta)); //console: [] var spaghetti = new Pasta("Tom", 20, "male"); console.log(Object.keys(spaghetti)); //console: ["name", "age", "gender", "toString"]
数组,返回索引
var arr = ["a", "b", "c"]; console.log(Object.keys(arr)); // console: ["0", "1", "2"]
如何判断一个对象是否为空
遍历key:Object.keys()
遍历值:Object.values()
遍历Key和值:Object.entries
作者:rosenWang
链接:https://juejin.im/post/5c078dc56fb9a049a570af3a
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文:https://www.cnblogs.com/azhqiang/p/12884169.html