首页 > 解决方案 > 是否可以在 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])
  }
}

标签: javascriptfor-loopobjectiteration

解决方案


根据您的问题,我猜您期望该函数会被实际调用。

为此,您需要检查 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;
    }

推荐阅读