JavaScript:Map根据值查找对应的键
Map根据值查找键,可以使用for..of迭代Map的Entry,再判断Entry的值:
键值一对一
function getByValue(map, searchValue) {
for (let [key, value] of map.entries()) {
if (value === searchValue)
return key;
}
}
let map= new Map();
map.set('1', 'red');
map.set('2', 'blue');
map.set('3', 'green');
console.log(getByValue(map, 'blue'))
console.log(getByValue(people, 'red'))
键值一对多
function getByValue(map, searchValue) {
let keys = [];
for (let [key, value] of map.entries()) {
if (value === searchValue)
keys.push(key);
}
return keys;
}