Saturday, 29 April 2017

Javascript object forEach howto?




In the following JavaScript code,



obj = {};

// This work as intented
obj['a'] = { item1: 'a1', item2: 'a2' };
console.log(obj);


// Object.keys() works too
console.log(Object.keys(obj));

// forEach does not, why? and how to fix?
console.log('forEach');
obj.forEach(o => console.log(o));


What is needed to have forEach working?



Answer



What you have here is a JavaScript question, not a TypeScript question. TS and JS have the same runtime semantics.



forEach is a method of Array. Objects don't have forEach. The semantics of forEach don't make sense on regular objects -- your obj doesn't have a length or a 0 property, for example, which are the kinds of things forEach looks for.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...