gpt4 book ai didi

javascript - 如何在javascript中迭代到对象方法

转载 作者:行者123 更新时间:2023-12-04 13:12:49 24 4
gpt4 key购买 nike

let person = {
firstName: "Rella",
lastName: "binson",
age: 18,
getFullName: function() {
return this.firstName + ' ' + this.lastName;
}
};

for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ' ' + person[key])
}
}
// it doesn't print 'getFullName()

最佳答案

考虑使用 getter 属性:

let person = {
firstName: "Rella",
lastName: "binson",
age: 18,
get getFullName() {
return this.firstName + ' ' + this.lastName;
}
};

for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ' ' + person[key])
}
}

引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

关于javascript - 如何在javascript中迭代到对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63298457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com