在 JavaScript 中,遍历一个 对象 的 属性 可以使用 ownKeys() 方法,Reflect.ownKeys 返回一个 数组,该数组包含对象自身的所有键名,不管键名是 Symbol 或 字符串,也不管是否可枚举。
Reflect.ownKeys(obj);
参数 | 描述 |
---|---|
obj | 需要遍历的对象。 |
返回一个数组,该数组包含对象自身的所有键名,不管键名是 Symbol 或字符串,也不管是否可枚举。
使用 Reflect.ownKeys 遍历对象属性
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Reflect.ownKeys遍历对象属性</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function createPerson(name, age, sex){
var person = new Object();
person.name = name;
person.age = age;
person.sex = sex;
person.sayHi = function(){
console.log("I am", this.name, "i am", this.age, "years old", "and my sex is", this.sex);
}
return person;
}
var person = createPerson("HaiCoder", 109, "F");
var keys = Reflect.ownKeys(person);
console.log("Keys =", keys);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们使用 Reflect.ownKeys 方法获取了对象的所有的属性的键组成的数组。
使用 Reflect.ownKeys 遍历对象属性
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Reflect.ownKeys遍历对象属性</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function createPerson(name, age, sex){
var person = new Object();
person.name = name;
person.age = age;
person.sex = sex;
person.sayHi = function(){
console.log("I am", this.name, "i am", this.age, "years old", "and my sex is", this.sex);
}
return person;
}
var person = createPerson("HaiCoder", 109, "F");
var keys = Reflect.ownKeys(person);
for(var key of keys){
console.log("Person Key =", key, "Value =", person[key]);
}
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们使用 Reflect.ownKeys 方法获取了对象的所有的属性的键组成的数组,接着,使用数组的 for of 方法,遍历了数组的所有的值,从而遍历了对象的所有属性。
使用 Reflect.ownKeys 遍历对象属性
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Reflect.ownKeys遍历对象属性</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function createPerson(name, age, sex){
var person = new Object();
person.name = name;
person.age = age;
person.sex = sex;
person.sayHi = function(){
console.log("I am", this.name, "i am", this.age, "years old", "and my sex is", this.sex);
}
return person;
}
var person = createPerson("HaiCoder", 109, "F");
Reflect.ownKeys(person).map((key) => {
console.log("Person Key =", key, "Value =", person[key]);
})
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们使用 Reflect.ownKeys 方法获取了对象的所有的属性的键组成的数组,接着,使用数组的 map 函数,根据数组的 key 遍历了数组的所有属性和属性的值。
在 JavaScript 中,遍历一个对象的属性可以使用 ownKeys() 方法,Reflect.ownKeys 返回一个数组,该数组包含对象自身的所有键名,不管键名是 Symbol 或字符串,也不管是否可枚举。