对象判断属性是否存在
Object.prototype.hobby = 'basketball' const mySymbol = Symbol('本对象上的可遍历symbol值') const mySymbol2 = Symbol('本对象上的不可遍历symbol值') const mySymbol3 = Symbol('Object.prototype定义的symbol值') Object.prototype[mySymbol3] = 'i am a symbol3333' const foo = { name:'kobe', age:18, [mySymbol]:'i am a symbol', } Object.defineProperty(foo,'address',{ configurable:true, enumerable:false, writable:true, value:'xxxxxxx' }) Object.defineProperty(foo,mySymbol2,{ configurable:true, enumerable:false, writable:true, value:'i am symbol2222222' }) console.log(Object.getPrototypeOf(foo)); // foo现在一共六个属性, // address属性不可枚举,hobby属性在原型上;mysymbol是可遍历的symbol值,mysymbol是不可遍历的symbol值; console.log(foo.hasOwnProperty('name')); // true console.log(foo.hasOwnProperty('address')); //true console.log(foo.hasOwnProperty(mySymbol)); //true console.log(foo.hasOwnProperty('hobby')); //false //担心hasOwnProperty被重写,可以用这个方法;console.log(Object.prototype.hasOwnProperty.call(foo,'name')) //true for (const key in foo) { console.log(key); //name age hobby }
console.log(Object.keys(foo)); //[ 'name', 'age' ]
console.log(Object.getOwnPropertyNames(foo)); //[ 'name', 'age', 'address' ] console.log(Object.getOwnPropertySymbols(foo)); //[ Symbol(mySymbol), Symbol(mySymbol22222) ] console.log(Object.getOwnPropertyDescriptors(foo)); // name: { // enumerable: true,。。。。。。。。。 // }, // age: { value: 18, writable: true, enumerable: true, configurable: true }, // address: { // enumerable: false,。。。。。。。。 // }, // [Symbol(mySymbol)]: { // enumerable: true,。。。。。。。。 // }, // [Symbol(mySymbol22222)]: { // enumerable: false, // } // } //IN 刚好相反:会遍历到可枚举的东西,但是会遍历原型, SYMBOL不可以遍历 //总结:这四个都不可以遍历原型;
//Object.keys() 会遍历可枚举的属性,不可遍历symbol,不会遍历原型;
//Object.prototype.hasOwnProperty会遍历到不可枚举的东西,但是不会遍历原型, SYMBOL可以遍历 这个方法和getOwnPropertyDescriptors很像,只不过这个只是单纯的判断是否存在,只是单纯的反回boolean; // Object.getOwnPropertyNames 可以遍历不可枚举的东西,但是不会遍历原型,不能symbol // Object.getOwnPropertySymbols 可以遍历不可枚举的symbol;不遍历原型;之遍历symbol; // Object.getOwnPropertyDescriptors 会遍历到不可枚举的东西,不会遍历原型, 遍历symbol 这个方法就是上面两个的合体;
分类:
随笔
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!