Map

  1. let myMap = new Map();
  2. let keyObj = {};
  3. let keyFunc = function() {};
  4. let keyString = 'a string';
  5. // 添加键
  6. myMap.set(keyString, "和键'a string'关联的值");
  7. myMap.set(keyObj, "和键keyObj关联的值");
  8. myMap.set(keyFunc, "和键keyFunc关联的值");
  9. myMap.size; // 3
  10. // 读取值
  11. myMap.get(keyString); // "和键'a string'关联的值"
  12. myMap.get(keyObj); // "和键keyObj关联的值"
  13. myMap.get(keyFunc); // "和键keyFunc关联的值"
  14. myMap.get('a string'); // "和键'a string'关联的值"
  15. // 因为keyString === 'a string'
  16. myMap.get({}); // undefined, 因为keyObj !== {}
  17. myMap.get(function() {}); // undefined, 因为keyFunc !== function () {}
方法 描述
clear() 删除 Map 中的所有元素。
delete() 删除由键指定的元素。
has() 如果键存在,则返回 true。
forEach() 为每个键/值对调用回调。
属性 描述
size 获取 Map 中键的值。
  1. mp.size;
  2. fruits.delete(apples);
  3. fruits.clear();
  4. fruits.has(apples);
  5. // 若Map中含有键,返回true

set

  1. // 创建新的变量
  2. const a = "a";
  3. const b = "b";
  4. const c = "c";
  5. // 创建 Set
  6. const letters = new Set();
  7. // Add the values to the Set
  8. letters.add(a);
  9. letters.add(b);
  10. letters.add(c);
  11. // 创建新的 Set
  12. const letters = new Set(["a","b","c"]);
  13. typeof letters; // 返回 object。
  14. 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 最长连续序列

  1. var longestConsecutive = function(nums) {
  2. const set = new Set(nums);
  3. let ans = 0;
  4. for(const num of nums) {
  5. if(!set.has(num-1)) {
  6. let count = 1,cur = num;
  7. while(set.has(cur + 1)) {
  8. cur++;
  9. count++;
  10. }
  11. ans = Math.max(ans,count);
  12. }
  13. }
  14. return ans;
  15. };