JavaScript中的Object对象有许多内置方法,以下是其中一些常用的方法:
-
Object.keys(obj)
- 返回一个包含给定对象的所有可枚举属性的字符串数组。
javascriptCopy code const obj = { a: 1, b: 2, c: 3 }; const keys = Object.keys(obj); // keys: ['a', 'b', 'c'] -
Object.values(obj)
- 返回一个包含给定对象的所有可枚举属性值的数组。
javascriptCopy code const obj = { a: 1, b: 2, c: 3 }; const values = Object.values(obj); // values: [1, 2, 3] -
Object.entries(obj)
- 返回一个包含给定对象的所有可枚举属性的键值对数组。
javascriptCopy code const obj = { a: 1, b: 2, c: 3 }; const entries = Object.entries(obj); // entries: [['a', 1], ['b', 2], ['c', 3]] -
Object.assign(target, source1, source2, ...)
- 将一个或多个源对象的属性复制到目标对象。返回目标对象。
javascriptCopy code const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; const result = Object.assign(target, source); // target: { a: 1, b: 3, c: 4 } // result: { a: 1, b: 3, c: 4 } -
Object.create(proto, [propertiesObject])
- 使用指定的原型对象和属性创建一个新对象。
javascriptCopy code const protoObj = { x: 10 }; const newObj = Object.create(protoObj); // newObj: {} // newObj.__proto__: { x: 10 } -
Object.hasOwnProperty(prop)
- 返回一个布尔值,指示对象是否具有指定的属性。
javascriptCopy code const obj = { a: 1, b: 2 }; const hasProperty = obj.hasOwnProperty('a'); // hasProperty: true