JavaScript中属性遍历的三种方法分别是for...in循环、Object.keys()方法和Object.getOwnPropertyNames()方法。下面是对应的例子:
- for...in循环:
let obj = {name: "Alice", age: 25, gender: "Female"}; for(let prop in obj){ console.log(prop + ": " + obj[prop]); }
输出结果:
name: Alice age: 25 gender: Female
- Object.keys()方法:
let obj = {name: "Alice", age: 25, gender: "Female"}; let props = Object.keys(obj); for(let i = 0; i < props.length; i++){ console.log(props[i] + ": " + obj[props[i]]); }
输出结果:
name: Alice age: 25 gender: Female
- Object.getOwnPropertyNames()方法:
let obj = {name: "Alice", age: 25, gender: "Female"}; let props = Object.getOwnPropertyNames(obj); for(let i = 0; i < props.length; i++){ console.log(props[i] + ": " + obj[props[i]]); }
输出结果:
name: Alice age: 25 gender: Female