嗨,我在学Js,所以请友好一点。我刚刚了解了对象内部的函数或方法。
我试图循环这个基本对象,最后一个键'calcAge‘是一个应该输出'30’的函数,从底部的console.log中可以看到。但是for循环输出整个函数。我怎样才能把它输出到30?
let currentYear = 2021;
const myFriends = {
firstName: 'Alan',
lastName: 'Snape',
job: 'teacher',
birthYear: 1991,
friends: ['geoff', 'dave', 'sean'],
hasLicense: true,
calcAge: function (birthYear) {
myFriends.age = currentYear - this.birthYear;
return this.age;
},
};
for (let i in myFriends) {
console.log(`${i} : ${myFriends[i]}`);
}
// firstName: 'Alan',
// lastName: 'Snape',
// job: 'teacher',
// birthYear: 1991,
// friends: ['geoff', 'dave', 'sean'],
// hasLicense: true,
// calcAge: function (birthYear) {
// myFriends.age = currentYear - this.birthYear;
// return this.age;
// },
// };
console.log(myFriends.calcAge()); //30发布于 2021-12-14 04:45:56
为了在迭代对象时获得30,您应该检查属性值是否是一个函数,如果它是一个函数,您可以调用它来获得函数结果,否则可以直接记录该值,如下所示:
for (let i in myFriends) {
console.log(`${i} : ${typeof myFriends[i] == 'function' ? myFriends[i]() : myFriends[i]}`);
}发布于 2021-12-14 04:48:45
您应该将calcAge函数修复为如下所示:
calcAge : function () {
this.age = currentYear - this.birthYear;
return this.age;
}发布于 2021-12-14 04:49:58
当您循环遍历一个对象并尝试访问一个键的值时,您基本上是指向键的值,仅此而已。您可以观察到,这些值是正确打印的,这些值是非函数的,或者那些不需要对它们进行任何进一步操作的值(即数组、字符串、数字)。但是,当该值是一个函数时,您将得到它的打印,因为它只是指向该函数,而不是调用它。要获得所需的结果,只需检查该值是否为函数。如果它是一个函数,那么执行它,或者按原样打印。
let currentYear = 2021;
const myFriends = {
firstName: 'Alan',
lastName: 'Snape',
job: 'teacher',
birthYear: 1991,
friends: ['geoff', 'dave', 'sean'],
hasLicense: true,
calcAge: function (birthYear) {
myFriends.age = currentYear - this.birthYear;
return this.age;
},
};
for (let i in myFriends) {
if(typeof myFriends[i]==='function'){ //Check if the value is a function.
console.log(`${i} : ${myFriends[i]()}`); //Execute the function.
}
else{
console.log(`${i} : ${myFriends[i]}`); //Print the value directly if it is not a function.
}
}https://stackoverflow.com/questions/70343861
复制相似问题