SET和MAP

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
<script>

//     set:数组和对象的映射,或抽象
    var s = new Set(["hello",7,"world",7,"world",7,"world"]);
     console.log(s);//{"hello", 7, "world"} set不会重复
    console.log(typeof s);//object
     console.log(s[0]);//u
     console.log(s[1]);//u
     console.log(s[2]);//u
     console.log(s.length);//u
     for(var i of s){
         console.log(i)//hello 7 world
     }
     var s = new Set();
     s.add(3)
     s.add(4)
     s.add(5)
     s.add("3")
     console.log(s)//Set(4) {3, 4, 5, "3"}//  Set集合是默认去重复的,但前提是两个添加的元素严格相等 所以3和"3"不相等,两个new出来的字符串不相等

         for(var i of s.keys()){ //数组keys就是他本身
         console.log(i) //3 4 5 3
     }
     for(var i of s.values()){
         console.log(i) //3 4 5 3
     }
     for(var i of s.entries()){
         console.log(i)//[3,3]  [4,4]  [5,5]  [3,3]
     }


    // map    关于遍历的方法 由于Set集合本质上还是一个map,因此会有以下几种奇怪的遍历方法
    var m = new Map();
    m.set("name","admin");
    m.set("age",18);

     console.log(m);//Map(2) {"name" => "admin", "age" => 18} //不是箭头函数
     console.log(typeof m);//object

     console.log(m.get("name"));//admin
     console.log(m.get("age"));//18

     console.log(m.name); //undefined
     console.log(m.age);//u

     for(var i of m){
         console.log(i) // ["name", "admin"]  ["age", 18]

     }
     for(var i of m.keys()){
         console.log(i) //name age
     }
     for(var i of m.values()){
         console.log(i) //admin 18
     }
     for(var i of m.entries()){
         console.log(i) //["name", "admin"]  ["age", 18]
     }



</script>
</html>

 

posted @ 2019-08-30 16:57  菜鸟小何  阅读(381)  评论(0编辑  收藏  举报