const blogPost={ id:1, title: "JavaScript教程", getSlug: function(){ return "/post/"+this.title; }, author: "李明", comments: ["很好","受教了","加油"], "update-at": "2020-10-26" }; console.log(Object.keys(blogPost)); Object.keys(blogPost).forEach((key)=>{ console.log(`${key}:${blogPost[key]}`); });输出结果为:
['id','title','getSlug','author','comments','update-at'] id:1 title:JavaScript教程 getSlug:function(){ return "/post/"+title; } author:李明 comments:很好,受教了,加油 update-at:2020-10-26第一行输出了 Object.keys(blogPost) 的值,可以看到对象中的属性名以数组的形式返回了,后面代码遍历了这个数组,并用遍历到的元素作为属性名去对象中获取属性值,并打印出了字符串结果。
//...省略blogPost定义 for(let key in blogPost){ console.log(`${key}:${blogPost[key]}`); }输出结果与上例一样。
Object.getOwnPropertyNames(blogPost).forEach(key=>{ console.log(`${key}:${blogPost[key]}`); })
const obj={ a:1, [Symbol('b')]:2, [Symbol('c')]:3, } Object.getOwnPropertySymbols(obj); //[Symbol(b),Symbol(c)]
本文链接:http://task.lmcjl.com/news/14462.html