JavaScript中的Object.getOwnPropertyNames()方法是標準的內置對象,該對象返回給定對象中存在的所有屬性。
用法:
Object.getOwnPropertyNames(obj)
參數:此方法接受上述和以下描述的單個參數:
- obj:此參數保存要返回其可枚舉和不可枚舉屬性的對象。
返回值:此方法返回一個字符串數組,該字符串數組對應於直接在給定對象中找到的屬性。
以下示例說明了JavaScript中的Object.getOwnPropertyNames()方法:
範例1:
const gfg = {
val1:"Geek1",
val2:"Geek2",
val3:"Geek3",
val4:"Geek4"
};
console.log(Object.getOwnPropertyNames(gfg));
var gfg2 = { val1:'Geek1', val2:'Geek2', val3:'Geek3' };
console.log(Object.getOwnPropertyNames(gfg2).sort());
Object.getOwnPropertyNames(gfg2).
forEach(function(val, idx, array) {
console.log(val + ' -> ' + gfg2[val]);
});
輸出:
Array ["val1", "val2", "val3", "val4"] Array ["val1", "val2", "val3"] "val1 -> Geek1" "val2 -> Geek2" "val3 -> Geek3"
範例2:
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function() {};
function ChildClass() {
this.prop = 5;
this.method = function() {};
}
ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function() {};
console.log(
Object.getOwnPropertyNames(
new ChildClass()
)
);
var my_obj = Object.create({}, {
getFoo:{
value:function() { return this.foo; },
enumerable:false
}
});
my_obj.foo = 1;
console.log(Object.getOwnPropertyNames(my_obj).sort());
輸出:
Array ["prop", "method"] Array ["foo", "getFoo"]
支持的瀏覽器:下麵列出了Object.getOwnPropertyNames()方法支持的瀏覽器:
- 穀歌瀏覽器
- Firefox
- IE
- Opera
- Safari
- Edge
相關用法
- Javascript Uint8Array.from()用法及代碼示例
- Javascript padEnd()用法及代碼示例
- Javascript Float64Array.from()用法及代碼示例
- Javascript Uint8ClampedArray.from()用法及代碼示例
- Javascript padStart()用法及代碼示例
- Javascript Int16Array from()用法及代碼示例
- Javascript Uint32Array from()用法及代碼示例
- Javascript Replace()用法及代碼示例
- Javascript Reflect.has()用法及代碼示例
- Javascript Promise.all()用法及代碼示例
- Javascript compile()用法及代碼示例
- Javascript Array from()用法及代碼示例
- Javascript hasOwnProperty()用法及代碼示例
- Javascript Array map()用法及代碼示例
- Javascript exec()用法及代碼示例
注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 JavaScript | Object.getOwnPropertyNames() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。