The enumerate function in Javascript
- Time:2020-09-16 12:48:17
- Class:Weblog
- Read:31
In Python, the enumerate function is an iterator that returns/yield each time a tuple that contains an index (starting from 0 and incrementing) and the element in the list.
In Javascript, we can implement the enumerate function using the iterator and the yield keyword (the asteroid star immediate after function keyword indicates that the function should return an iterator via the yield keyword).
1 2 3 4 5 | function *enumerate(array) { for (let i = 0; i < array.length; i += 1) { yield [i, array[i]]; } } |
function *enumerate(array) { for (let i = 0; i < array.length; i += 1) { yield [i, array[i]]; } }
Since Javascript does not have a Tuple-type, but we can use array anyway. We can use the defined enumerate function like below:
1 2 3 4 | const list = ['a', 'b', 'c']; for (let x of enumerate(list)) { console.log(x); } |
const list = ['a', 'b', 'c']; for (let x of enumerate(list)) { console.log(x); }
That should output the following:
1 2 3 | [0, 'a'] [1, 'b'] [2, 'c'] |
[0, 'a'] [1, 'b'] [2, 'c']
As you can see, the incrementing index is coupled with the element in the original list/array.
Also, we can use the iterator.next() function until iterator.done is true.
1 2 3 4 5 6 | let it = enumerate(['a', 'b', 'c', 'd']) let result = it.next(); while (!result.done) { console.log(result.value) result = it.next(); } |
let it = enumerate(['a', 'b', 'c', 'd']) let result = it.next(); while (!result.done) { console.log(result.value) result = it.next(); }
This should print the following:
1 2 3 4 | [ 0, 'a' ] [ 1, 'b' ] [ 2, 'c' ] [ 3, 'd' ] |
[ 0, 'a' ] [ 1, 'b' ] [ 2, 'c' ] [ 3, 'd' ]
–EOF (The Ultimate Computing & Technology Blog) —
Recommend:Switching to a Blogging Career: Can You Afford to Work from Home
4 Features that Will Enhance Your Blog
Amazon Surpasses Google: Should you Change your SEO Strategies?
How to Optimize WordPress Categories and Tags
Blogging Royalties: Michelle Obama Interviewing Barack on her Po
Content Marketing: Expectations Vs Reality
Blogger Skills: LinkedIn and Microsoft’s Digital Skill Programs
5 Tips for Creating a Content Strategy for Your eCommerce Websit
5 Tips You Can Use to Launch a Successful Property Management Bl
Blogging and Gaming Finally Recognized as Professions
- Comment list
-
- Comment add