假设有一个对象:
const myObj = {
name: 'Tom',
age: 25,
gender: 'male'
};
const myKey = 'age';
for(let key in myObj) {
if(key === myKey) {
console.log(`The value of ${myKey} is ${myObj[key]}`);
}
}
输出:
The value of age is 25
const myKey = 'age';
Object.keys(myObj).forEach(key => {
if(key === myKey) {
console.log(`The value of ${myKey} is ${myObj[key]}`);
}
});
输出:
The value of age is 25
const myKey = 'age';
Object.entries(myObj).forEach(([key, value]) => {
if(key === myKey) {
console.log(`The value of ${myKey} is ${value}`);
}
});
输出:
The value of age is 25
上一篇:遍历对象并选择最后一个对象
下一篇:遍历对象并只显示重复的值一次