The enumerate function in Javascript
- 时间:2020-09-16 12:48:17
- 分类:网络文摘
- 阅读:144 次
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) —
推荐阅读:百度算法经常更新要怎么解决? 讲一讲我这10年的站长经历 为什么企业网站不要用模板建站 模板建站有哪些弊端 网站安全渗透测试难度系数有多大 什么内容才是被百度肯定的优质内容?优质内容应该这样做! seo-网站权重怎么提高? 万词霸屏与SEO优化合二为一才能给企业带来真实效益 熟知百度蜘蛛原理,按照优化规则才能做好seo优化 SEO关键词排名优化原理是什么? 织梦程序如何调用自定义字段?
- 评论列表
-
- 添加评论