简体   繁体   中英

How to iterate through functions defined in a javascript object

I have an object that defines a bunch of functions like this:

myObject = {
  "item 1": function() {
    return "I'm item 1";
  },
  "item 2": function() {
    return "I'm item 2";
  }
};

I want to write a function that calls all of the functions defined in this object without having to know the names of the functions or the number of functions. Is this possible?

In ECMAScript >=5.1 you can use the for .. in construct.

obj = {
    test : function() {
        console.log("test called");
    }
};

for(idx in obj) {
    obj[idx]();
}

You may want to check that the property is actually a function.

You can do this by first using a for-in loop to go through each of the objects properties. Then, after checking if the value is a function, you can call it.

for (var key in obj) {
  if (typeof obj[key] === 'function') {
    obj[key]();
  }
}

You could either use Object.keys or a for-in loop depending on your needs.

Object.keys(obj); // ==> ["item-1", "item-2"]
Object.keys(obj).forEach(function (key) {
    var fn = obj[key];
    fn();
});

// or with a for-in loop

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        obj[key]();
    }
}

Using Object.keys is arguably a bit more clear, but the for-in loop has better browser compatibility and possibly performance. For a more general comparison of object enumeration in JavaScript, refer to this question How do I enumerate the properties of a JavaScript object? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM