如何在 Javascript 的 MAP 中检查 VALUE 是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50077120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if an VALUE exists in MAP on Javascript?
提问by Fernando Maymone
It looks a very easy question but i didnt find it in any place.
这看起来是一个非常简单的问题,但我没有在任何地方找到它。
How can I know If an value exists in a Map?
我如何知道 Map 中是否存在某个值?
For example:
例如:
A = [1,2,3,5,6,7]
var myMap = new Map();
for (let i = 0; i < A.length; i++) {
myMap.set(i,A[i]);
}
for (let z = 1; z < Number.MAX_SAFE_INTEGER; z++) {
console.log(z);
if(!myMap.hasValue(z)){
return z;
}
}
I want to check if, given one value, this VALUE is on the Hash. Like a "hasValue"
我想检查给定一个值,这个 VALUE 是否在哈希上。就像一个“hasValue”
采纳答案by Dario
You can use iterate over the map, look for the value and return true (exiting the loop) as soon as you find it. Or you return false if the element does not exist. Something like:
您可以在地图上使用迭代,查找值并在找到后立即返回 true(退出循环)。或者,如果元素不存在,则返回 false。就像是:
const findInMap = (map, val) => {
for (let [k, v] of map) {
if (v === val) {
return true;
}
}
return false;
}
回答by Bergi
You cannot, other than by searching through it:
除了通过搜索之外,您不能:
Array.from(myMap.values()).includes(val)
Use an appropriate data structure instead, like a set of all the values:
改用适当的数据结构,例如所有值的集合:
A = [1,2,3,5,6,7]
var myValues = new Set(A);
for (let z = 1; z < Number.MAX_SAFE_INTEGER; z++) {
console.log(z);
if(!myValues.has(z)) {
return z;
}
}
Of course, given the fact that your Ais sorted already, you could iterate it directly to find the lowest missing value.
当然,鉴于您A已经排序,您可以直接迭代它以找到最低的缺失值。
回答by Johannes Nielsen
I know this question is already answered, but I would like to point out a way to do this without (explicitly) iterating of the entries. You can do
我知道这个问题已经得到回答,但我想指出一种无需(显式)迭代条目的方法。你可以做
let myMap = new Map([[0, 1], [1, 2], [2, 3], [3, 5], [4, 6], [5, 7]])
for (let z = 1; z < Number.MAX_SAFE_INTEGER; ++z) {
console.log(z);
if([...myMap.values()].includes(z) === false){
return z;
}
}
So, you could create a function
所以,你可以创建一个函数
const mapContainsElement = (map, val) => [...map.values()].includes(v)

![javascript 当通过 Selenium WebDriver 使用来自 JavascriptExecutor 接口的 executeScript 方法时,arguments[0] 和 arguments[1] 是什么意思?](/res/img/loading.gif)