[英]how to get keys and values from a Map(obj) in a loop (js)?
I try to get the key and values out of a map in a loop, in the second run the key and value is undefined. 我尝试在循环中从映射中获取键和值,在第二次运行中,键和值未定义。 any ideas? 有任何想法吗?
let map = new Map(); map.set('{{NAME}}', 'Name'); map.set('{{CLASS}}', 'Sorc'); let keyIterator = map.keys(); let valIterator = map.values(); let counter = map.size; for (let i = 0; i < counter; i++){ console.log('Key: ' + keyIterator.next().value); console.log('Val: ' + valIterator.next().value); }
Output: 输出:
Key: {{NAME}} 密钥:{{NAME}}
Val: Name 值:名称
Key: undefined 键:未定义
Val: undefined 值:未定义
I hope its not a duplicate, but i couldnt find an clear answer to my problem. 我希望它不是重复的,但是我找不到我问题的明确答案。
You could iterate the entries of map by using a for ... of
statement. 您可以使用for ... of
语句来迭代map的条目。
let map = new Map(); map.set('{{NAME}}', 'Name'); map.set('{{CLASS}}', 'Sorc'); for (let [k, v] of map) { console.log('Key: ' + k); console.log('Val: ' + v); }
Make it simple and just use the method of forEach
from Map object. 使它简单,只需使用Map对象中的forEach
方法即可。
let map = new Map(); map.set('{{NAME}}', 'Name'); map.set('{{CLASS}}', 'Sorc'); map.forEach((val,key) => { console.log(`Key: ${key}`) console.log(`Val: ${val}`) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.