JavaScript 对象(Objects) 方法

Object.getOwnPropertyNames()方法用于返回一个数组,其元素为对象的所有属性名,包括不可枚举的属性

语法:

Object.getOwnPropertyNames(obj)

参数:

obj:对象。

返回值:

此方法返回一个包含对象所有属性名的数组。

浏览器支持:

chrome5
edge是的
firefox4
opera12

示例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()); // 输出'0,1,2'
// 使用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); 
// 检查字符串的第一个字符是否为“s”。
function CheckKey(value) {
    var firstChar = value.substr(0, 1); 
    if (firstChar.toLowerCase() == 's')
        return true; 
    else
        return false; 
}

输出:

size,shape