简体   繁体   English

如何检查地图打字稿中不存在的值?

[英]How to check for a non existing value in a map typescript?

I have the below map in typescript:我在打字稿中有以下地图:

myMap = {"a" => 1, "b" => 2, "c" => 4, "d" => 5} myMap = {"a" => 1, "b" => 2, "c" => 4, "d" => 5}

The values can be 1 , 2 , 3, 4, or 5 only.值只能是 1 、 2 、 3 、 4 或 5 。

I need to check for the values in the myMap from 1 to 5 and if any of the value is missing, i want to log it and exit the loop.我需要检查 myMap 中从 1 到 5 的值,如果缺少任何值,我想记录它并退出循环。 Eg: In the above map, value 3 is missing.例如:在上面的地图中,缺少值 3。 So, i would want to log that value.所以,我想记录这个值。

Can anyone let me know, how this could be achieved in typescript ?谁能让我知道,这是如何在打字稿中实现的?

You could create a Set of the values in Map .您可以在Map创建一Set values Then filter the numbers array and check if the set has each number然后filter数字数组并检查该集合has每个数字

 const numbers = [1, 2, 3, 4, 5], map = new Map([ ["a", 1], ["b", 2], ["c", 4] ]), set = new Set(map.values()), missing = numbers.filter(n => !set.has(n)) console.log(missing)

That something more javascript specific then typescript.那些比打字稿更特定于 javascript 的东西。

var myMap = new Map();
myMap.set("a", 1);
myMap.set("b", 2);

let hasThree = [...myMap.values()].includes(3);

console.log(hasThree);

You can use .values() and spread it into an array and use then .includes您可以使用.values()并将其传播到数组中,然后使用.includes

在此处输入图片说明

Here is an image that shows all methods of the Map prototype.这是一张显示 Map 原型的所有方法的图像。

Taking into consideration that values are 1 to 5 , you could change array as well and use some other values with specific range and use it with map with this -考虑到值是1 to 5 ,您也可以更改数组并使用具有特定范围的其他一些值并将其与map一起使用 -

 var map = new Map(); map.set('a', 1) map.set('b', 2) map.set('c',4) map.set('d', 5) var arr = []; for(var singleVal of map.values()) arr.push(singleVal) var originalArr = [ 1, 2, 3, 4, 5]; // taking into consideration that you have some original array like this, where '3' is present for(var i=0; i<originalArr.length; i++) if(!arr.includes(originalArr[i])) { console.log(originalArr[i]); break; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM