是否可以在for循环内迭代方法对象

时间:2020-08-07 09:19:53

标签: javascript for-loop object iteration

我想知道为什么在迭代对象时使用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])
  }
}

2 个答案:

答案 0 :(得分:0)

根据您的问题,我想您期望该函数真正被调用。

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

答案 1 :(得分:-1)

您可以将其用作<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--Stylesheets--> <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" /> <!--JS files--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <h2>Hoverable Dropdown</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <div class="dropdown"> <button class="dropbtn">Menu</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> </body> </html>

getter