javascript - 是否可以在 for 循环中迭代方法对象
问题描述
我想知道为什么在迭代对象时使用 for 循环不显示方法。
请检查以下getFullList
未列出方法的示例:
let list = {
firstElement: "Element 1",
secondElement: "Element 2",
thirdElement: "Element 3",
getFullList: function() {
return this.firstElement + ', ' + this.secondElement + ', ' + this.thirdElement;
}
};
for (let key in list) {
if (list.hasOwnProperty(key)) {
console.log(key + ' ' + list[key])
}
}
解决方案
根据您的问题,我猜您期望该函数会被实际调用。
为此,您需要检查 list[key] 的类型并实际调用该函数
const list = {
firstElement: "Element 1",
secondElement: "Element 2",
thirdElement: "Element 3",
getFullList: function() {
return this.firstElement + ', ' + this.secondElement + ', ' + this.thirdElement;
}
};
for (const key in list) {
if (list.hasOwnProperty(key)) {
const value = list[key];
console.log(key + " " + value);
if (typeof value === "function") {
value();
}
}
}
将函数记录为“getFullList”的值时的控制台输出将类似于
ƒ () {
return this.firstElement + ', ' + this.secondElement + ', ' + this.thirdElement;
}
推荐阅读
- python - 无法在 Pycharm 中运行 urllib.request
- python - Python apscheduler 立即启动函数,不在给定时间启动?
- wpf - 如何突出显示 ItemsControl WPF 中的特定内容元素项?
- sql - oracle plsql可以从邮件中读取excel文件附件吗
- php - 如何根据数量更新商品的总价?
- firebase - FlutterFire - 在哪里获取验证码 # 通过 FirebaseAuth 上的电子邮件
- python - 使用 Python 通过流将数据从 S3 传输到 FTP 服务器
- flutter - Flutter sms_autofill 并不总是自动读取 OTP
- node.js - 是否可以在 Cloud Task 中从 Google Cloud Storage 安排 maven jar 文件?
- angular - 在 iis 上发布 Angular 应用程序 - 仅在 iis 端出错