Map
let myMap = new Map();let keyObj = {};let keyFunc = function() {};let keyString = 'a string';// 添加键myMap.set(keyString, "和键'a string'关联的值");myMap.set(keyObj, "和键keyObj关联的值");myMap.set(keyFunc, "和键keyFunc关联的值");myMap.size; // 3// 读取值myMap.get(keyString); // "和键'a string'关联的值"myMap.get(keyObj); // "和键keyObj关联的值"myMap.get(keyFunc); // "和键keyFunc关联的值"myMap.get('a string'); // "和键'a string'关联的值" // 因为keyString === 'a string'myMap.get({}); // undefined, 因为keyObj !== {}myMap.get(function() {}); // undefined, 因为keyFunc !== function () {}
| 方法 |
描述 |
| clear() |
删除 Map 中的所有元素。 |
| delete() |
删除由键指定的元素。 |
| has() |
如果键存在,则返回 true。 |
| forEach() |
为每个键/值对调用回调。 |
mp.size;fruits.delete(apples);fruits.clear();fruits.has(apples);// 若Map中含有键,返回true
set
// 创建新的变量const a = "a";const b = "b";const c = "c";// 创建 Setconst letters = new Set();// Add the values to the Setletters.add(a);letters.add(b);letters.add(c);// 创建新的 Setconst letters = new Set(["a","b","c"]);typeof letters; // 返回 object。letters instanceof Set; // 返回 true
Set 对象的方法和属性
| new Set() |
创建新的 Set 对象。 |
| add() |
向 Set 添加新元素。 |
| clear() |
从 Set 中删除所有元素。 |
| delete() |
删除由其值指定的元素。 |
| entries() |
返回 Set 对象中值的数组。 |
| has() |
如果值存在则返回 true。 |
| forEach() |
为每个元素调用回调。 |
| keys() |
返回 Set 对象中值的数组。 |
| values() |
与 keys() 相同。 |
| size |
返回元素计数。 |
leetcode 128 最长连续序列
var longestConsecutive = function(nums) { const set = new Set(nums); let ans = 0; for(const num of nums) { if(!set.has(num-1)) { let count = 1,cur = num; while(set.has(cur + 1)) { cur++; count++; } ans = Math.max(ans,count); } } return ans;};