Object.getOwnPropertyNames()
方法返回给定对象中所有属性的数组。
示例
const obj = {
name: 'Alexander',
age: 32,
address: 'Macedonia',
};
// find out the properties present in obj
const propertyNames = Object.getOwnPropertyNames(obj);
console.log(propertyNames);
// Output: [ 'name', 'age', 'address' ]
getOwnPropertyNames() 语法
getOwnPropertyNames()
方法的语法是
Object.getOwnPropertyNames(obj)
这里,getOwnPropertyNames()
是一个静态方法。因此,我们需要使用类名 Object
来访问该方法。
getOwnPropertyNames() 参数
getOwnPropertyNames()
方法接受
- obj - 要返回其属性的对象。
getOwnPropertyNames() 返回值
getOwnPropertyNames()
方法返回一个包含给定对象中属性对应的字符串的数组。
示例 1:JavaScript Object.getOwnPropertyNames()
// create an object
const obj = {
name: "Jack",
address : "London",
age: 22,
}
// returns the array of properties of obj
let objProperties = Object.getOwnPropertyNames(obj);
console.log(objProperties);
// Output: [ 'name', 'address', 'age' ]
在上面的示例中,我们使用了带有 obj 对象的 getOwnPropertyNames()
,它返回一个包含所有属性名或键的数组。
结果存储在 objProperties 对象中,当输出到控制台时,显示指定的数组。
示例 2:getOwnPropertyNames() 与类数组对象
// array-like object
let obj = { 75: "A", 67: "C", 66: "B" };
// get the property names of obj
console.log(Object.getOwnPropertyNames(obj));
// Output: [ '66', '67', '75' ]
在上面的示例中,我们创建了一个类数组对象 obj,其中包含随机整数作为键。
当与 obj 一起使用时,getOwnPropertyNames()
方法返回一个按升序排列的数字字符串数组。
示例 3:getOwnPropertyNames() 与数组
// create an array
let arr = ["a", "b", "c"];
// get the property names of arr
console.log(Object.getOwnPropertyNames(arr));
// Output: [ '0', '1', '2', 'length' ]
在上面的示例中,我们使用了名为 arr 的数组和 getOwnPropertyNames()
来查找数组中存在的属性。
输出包括数组的索引以及 length 属性。length
属性是 JavaScript 数组的内置属性,它返回数组中的元素数量。
示例 4:getOwnPropertyNames() 与不可枚举属性
// create an object
const obj = {
name: "Jack",
address : "London",
age: 22,
}
// defines the key girlFriend and
// sets enumerable as false
Object.defineProperty(obj, "girlFriend", {
value: "Jessica",
enumerable : false,
})
// prints the both enumerable and non-enumerable keys
console.log(Object.getOwnPropertyNames(obj));
// Output: [ 'name', 'address', 'age', 'girlFriend' ]
// print only the enumerable keys of obj
console.log(Object.keys(obj));
// Output: [ 'name', 'address', 'age' ]
在上面的示例中,我们首先创建了一个包含一些初始属性的对象 obj。
然后,我们使用 defineProperty() 方法添加了 girlFriend
属性,并将 enumerable 配置为 false
。
从输出中可以看出,Object.getOwnPropertyNames()
方法返回 obj 的可枚举和不可枚举属性。
另一方面,Object.keys() 方法仅返回可枚举属性。
请记住: Object.getOwnPropertyNames()
返回对象的所有可枚举和不可枚举属性,而 Object.keys()
返回对象的所有可枚举属性。
另请阅读