Iterable objects | Sololearn: Learn to code for FREE!


Iterable objects

How to make our own iterable object? I don't mean iterators and generators function. For eg, let el = document.getElementsByTagName("div"); The above code returns a iterable object. Weird thing is that, it's not actually instance of array, Array.isArray(el); // false el instanceof array ; // false let mkarr = [...el]; alert(mkarr.pop().innerHTML); //Returns html of last div element How to make our own iterable object? And, possibly, without inheriting Array object Edit: This way, we can make object iterable by inheriting Array object. Unfortunately, all properties and methods of Array object is now also of car() object

7/3/2019 9:13:41 AM

Sarthak Pokhrel

8 Answers

New Answer


Space {{#always_smile_ignore_situation😃😃}} Here are the requirements as I understand them. 1. Create an object that will behave like an indexable array of values. 2. Iterate the object such that only the indexable array elements are returned in each iteration. 3. This object should not be an Array or linked to an Array in the prototype chain. Essentially, this involves creating a custom generator function and binding it to the object as a method using Symbol.iterator as the key. *Add the following to your car constructor in the first code link you listed. //Implement a custom generator. this[Symbol.iterator] = function*() { for(let i in this) { //Yield only on numeric keys. if(Number(i) >= 0) yield this[i]; } } Here is a demo of this with several tests: P.S. - Dude... What's up with your long "message of the day" usernames?


Basel Al_hajeri.MBH() Still some confusion. In above code, how to make car() object/function iterable


daneillonge I know that. My question was, How to make our own object iterable? function car(){ this[0] = "BMW"; this[1] = "Ferrari"; this.length = 2; } var mycar = new car(); alert("All cars are: " + [...mycar].reduce((x,y)=>x+y)); I want to make car() object iterable, such that, above code outputs "BMWFerrari"


daneillonge . Htmlcollection,NodeList,HTMLAllCollection,...., behave like array, but are not inheriting from array object. I've shown a test in question above


getElementsByTagName return Html collection which is not an array or object prototype of javascript its an html collection of tags

+2 2nd lesson of this link/lesson


Space {{#always_smile_ignore_situation😃😃}} There are an overview in the like which I put u can search to learn more...


Space {{#always_smile_ignore_situation😃😃}} Object.keys(), Object.values(), Object.entries() alert("All cars are: " + Object.values(mycar).reduce((x,y)=>x+y));