Object.getOwnPropertyNames()函数详解

首页 / JavaScript入门教程 / Object.getOwnPropertyNames()函数详解

Object.getOwnPropertyNames()方法返回直接在给定对象上找到的所有属性的数组(使用符号的那些不可枚举的属性除外)。

语法

Object.getOwnPropertyNames(obj)

参数

obj :这是要返回其可枚举和不可枚举自身属性的对象。

返回值

此方法返回一个字符串数组,该字符串数组对应于直接在对象上找到的属性。

无涯教程网

浏览器支持

Chrome 5
Edge
Firefox 4
Opera 12

例子1

const object1 = {
  a: 0,
  b: 1,
  c: 2,
};
console.log(Object.getOwnPropertyNames(object1));

输出:

["a", "b", "c"]

例子2

 var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort());//logs '0,1,2'

// Logging property names and values using Array.forEach

Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  console.log(val + ' -> ' + obj[val]);

});

输出:

["0", "1", "2"]
 "0 -> a"
 "1 -> b"
 "2 -> c"    

例子3

function Pasta(grain, size, shape) {
    this.grain = grain; 
    this.size = size; 
    this.shape = shape; 
}
var spaghetti = new Pasta("wheat", 2, "circle");
var names = Object.getOwnPropertyNames(spaghetti).filter(CheckKey);
document.write(names); 
//Check whether the first character of a string is 's'. 
function CheckKey(value) {
    var firstChar = value.substr(0, 1); 
    if (firstChar.toLowerCase() == 's')
        return true; 
    else
         return false; }

输出:

size,shape

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

重学前端 -〔程劭非(winter)〕

Go语言从入门到实战 -〔蔡超〕

安全攻防技能30讲 -〔何为舟〕

接口测试入门课 -〔陈磊〕

深入浅出云计算 -〔何恺铎〕

SRE实战手册 -〔赵成〕

深入C语言和程序运行原理 -〔于航〕

AI 应用实战课 -〔黄佳〕

工程师个人发展指南 -〔李云〕

好记忆不如烂笔头。留下您的足迹吧 :)