Debugging with a for…in loopĪnother good use case for the JavaScript for.in loop is debugging. A for.in loop provides an easy way to iterate over an object’s properties and ultimately its values. Iterating objects with a JavaScript for…in loopīecause the for.in loop only iterates the enumerable properties of an object - which are the object’s own properties rather than properties like toString that are part of the object’s prototype - it’s good to use a for.in loop to iterate objects. Let’s look at the situations that the JavaScript for.in loop is best suited to. Inside the loop, we’re rendering the key, or index of each character, and the character at that index. In the following example, we’re looping over the variable obj and logging each property and value: const obj = //Output // "0: H" // "1: e" // "2: l" // "3: l" // "4: o" // "5: !" If you found this article helpful, please consider sharing it with others that could also find it helpful.When using for.in loop to iterate an object in JavaScript, the iterated keys or properties - which, in the snippet above, are represented by the key variable - are the object’s own properties.Īs objects might inherit items through the prototype chain, which includes the default methods and properties of Objects as well as Object prototypes we might define, we should then use hasOwnProperty. I found getting the index in a for-of loop a bit unintuitive, but, after playing around with it a bit, it is quite straight forward. If you run the above code, you should have the following output: bread at 0 Normally with a for-of loop you get the element value and not the element index. The first and easiest way to get the index with a for-of loop is to use the Array's built in keys function, like this: for (const index of shoppingList.keys()) `) Let's start with the data that I will be using: const shoppingList = [ In this tutorial I will show you two ways that you can get the index when using a for-of loop.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |