Iterable objects | Sololearn: Learn to code for FREE!

+10

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 https://code.sololearn.com/WZ6y8DltluPg/?ref=app 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 https://code.sololearn.com/WT9ReyUdjopb/?ref=app

7/3/2019 9:13:41 AM

Sarthak Pokhrel

8 Answers

New Answer

+9

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: https://code.sololearn.com/WI2JBp90wde1/?ref=app P.S. - Dude... What's up with your long "message of the day" usernames?

+7

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

+6

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"

+5

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

+3

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

+2

https://www.sololearn.com/learn/JavaScript/2981/ 2nd lesson of this link/lesson

+2

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

+2

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