es6新增数据结构map的用法

2019-12-26  本文已影响0人  郝艳峰Vip

前沿

搞开发就要不断的学习,不仅要不断学习,还要习惯做笔记,这样就会对一个知识点理解的更透彻,不过要是能够在项目中多多运用,那就理解的更透彻了。今天就来总结下es6新增的map的用法


step 一, map的特性

    let testMap = new Map();
        let abjkey = {
            keys:"123"
        };
        testMap.set(abjkey,'hello,map');
        console.log(testMap);
       console.log(testMap.get(abjkey));   //hello,map
     const testMap2 = new Map([
            ['testName', 'jack'],
            ['testAge', 13]
        ])
        console.log(testMap2.get('testName'))    //jack
        console.log(testMap2.get('age'))      //13
   const testMap2 = new Map();
        let testSet = {
            name: 'lasan',
            age: '21112'
        }
        testMap2.set(testSet,123456);
        console.log(testMap2.get(testSet));   //123456

step 二, 如何操作map,也就是map有那些方法

    const testMap3 = new Map();
        testMap3.set('test1', 1);
        testMap3.set('test12', 2);
        testMap3.set('test13', 3);
        console.log(testMap3.size)   //3
  const testMap3 = new Map();
        testMap3.set('test1', 1);    //键是字符串
        testMap3.set(22222, 66666);   //键是数值
        testMap3.set(undefined, 3333);   //键是 undefined
        const fun = function() { console.log('hello'); }
        testMap3.set(fun, 'fun') // 键是 function
        console.log(testMap3.get(undefined))    //66666
        console.log(testMap3.get(fun))      //3333

set还可以进行链式调用

testMap3.set().set().set()
  const testMap3 = new Map();
        testMap3.set('test1', 1);  
        console.log(testMap3.get(test1))      //1
  const testMap3 = new Map();
        testMap3.set('test1', 1);  
        console.log(testMap3.has(test1))      //true
  const testMap3 = new Map();
        testMap3.set('test1', 1);  
       testMap3.delete('test1');  
        console.log(testMap3.has(test1))      //false
testMap3.clear();
  const testMap3 = new Map();
        testMap3.set('test1', 1);    //键是字符串
        testMap3.set(22222, 66666);   //键是数值
        testMap3.set(undefined, 3333);   //键是 undefined
        const fun = function() { console.log('hello'); }
        testMap3.set(fun, 'fun') // 键是 function
      for (let item of testMap3.keys()) {
          console.log(item);    //test1,22222,undefined,fun
   }
   for (let item of testMap3.values()) {
          console.log(item);    //1,66666
}  
   for (let item of testMap3.entries()) {
          console.log(item);     //得到所有键值对 
      结果
                ["test1", 1]
                [22222, 66666]
                [undefined, 3333]
                [ƒ, "fun"]
}  
       for (let [key, value] of testMap3.entries()) {
            console.log(key, value);
        }
   //前边是key后边是value
           test1 1
       22222 66666
       undefined 3333
        ƒ fun() {
            console.log('hello');
        } "fun"

总结

目前小编了解的这么多,还是需要多多学习啊

上一篇下一篇

猜你喜欢

热点阅读