在 JavaScript 中,遍历一个 对象 的 属性 可以使用 getOwnPropertySymbols() 方法,Object.getOwnPropertySymbols() 方法会返回一个 数组,该数组包含了对象自身的所有 Symbol 属性的键名。
Object.getOwnPropertySymbols(obj);
参数 | 描述 |
---|---|
obj | 需要遍历的对象。 |
返回一个数组,该数组包含了对象自身的所有 Symbol 属性的键名。
使用 Object.getOwnPropertySymbols 遍历对象属性
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Object.getOwnPropertySymbols遍历对象属性</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 = Object.getOwnPropertySymbols(person);
console.log("Keys =", keys);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们使用 Object.getOwnPropertySymbols 方法 获取了对象的所有的 Symbol 属性的键组成的数组,因为此对象没有 Symbol 属性,因此,返回了空数组。
Object.getOwnPropertySymbols() 方法会返回一个数组,该数组包含了对象自身的所有 Symbol 属性的键名。