Es2015 set

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    
    <script>

        let arr = ['a','b','c','a'];
        console.log(arr); // (4) ["a", "b", "c", "a"]


        //类似于数组,但不能有重复的值,
        let setArr = new Set(['a','b','c','a']);
        // 添加数据
        setArr.add('e');
        console.log(setArr); // Set(4) {"a", "b", "c", "e"}
        
        console.log('---------------------------------');

        setArr.delete('a');
        console.log(setArr); // Set(3) {"b", "c", "e"}
        // 判断setArr有无此值
        console.log(setArr.has('f')); // false
        console.log(setArr.has('b')); // true
        // 获取setArr长度
        console.log(setArr.size); // 3

        // 清空所有
        // setArr.clear();
        // console.log(setArr);

        for(let item of setArr.entries()){
            console.log(item);
            // (2) ["b", "b"]
            // (2) ["c", "c"]
            // (2) ["e", "e"]
            // setArr.keys()  setArr.values() 结果都是 b、c、e
        }

        setArr.forEach((value,index)=>{
            console.log(value,index);
            // b b
            // c c
            // e e
        })

        // Set的应用之数组去重
        let arrr = [1,2,3,4,5,6,1,5,3,2,6,4,2,3,4]
        console.log(arrr);  // (15) [1, 2, 3, 4, 5, 6, 1, 5, 3, 2, 6, 4, 2, 3, 4]
        let newArr = new Set([...arrr]);
        console.log(newArr);    // (6) [1, 2, 3, 4, 5, 6]


        let arrr1 = new Set([1,2,3]);
        let arrr2 = new Set();
        for(let v of arrr1.values()){
            arrr2.add(v * 2);
        }
        console.log(arrr2); // Set(3) {2, 4, 6}

        let arrr3 = new Set([1,2,3,4]);
        let arrr4 = new Set([...arrr3].map(val=>val * 2));
        console.log(arrr4); // Set(4) {2, 4, 6, 8}
        let arrr5 = new Set([...arrr3].filter(val=>val %2 == 0));
        console.log(arrr5); // Set(2) {2, 4}

        // Set添加json
        let json1 = {
            a:1,
            b:2
        };
        let json2 = {
            a:8,
            b:9
        };
        let set1 = new Set();
        set1.add(json1);
        set1.add(json2);

        console.log(set1);

        set1.forEach((item)=>{
            console.log(item.a,item.b);
        })

        console.log("new WeakSet ===============================================");

        console.log("new WeakSet用法和 new Set一样但是没有size属性,没有卵用")





    </script>
</body>
</html>
Last modification:June 19th, 2019 at 09:51 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment