自学内容网 自学内容网

后盾人JS -- Set与WeakSet类型在JavaScript中的使用

Set类型与Array与Object对比分析

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let arr = [1,1,1,1,1,1]
        console.table(arr)
        
        let set = new Set([1,2,3,4,5])
        console.log(set)
        set.add(1)
        set.add(1)  //不可以有重复的
        console.log(set)

        let obj = {
            1:"hdcms",          //会被转成"1"
            "1":"houdunren"     
        }
        let hd = {
            [obj]:'后盾人'
        }
        console.log(hd[obj.toString()])
        console.log(hd)
    </script>
</body>
</html>

Set元素检测与管理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let set = new Set('houdunren','hscms')
        console.log(set.size)
        console.log(set.has("hdcms.com"))
        console.log(set.values())
        console.log(console.clear())
        console.log(set.size)
        console.log(set.delete("hdcms"))
    </script>
</body>
</html>

类型之间互相帮助才是好兄弟

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let set = new Set(['hdcms','houdunren'])
        console.log(Array.from(set))
        console.log([...set])
        let hd = new Set('123456789')
        //set过滤
        let arr = [... hd].filter(function(item){
            return item < 5
        })
        hd = new Set(arr)
        console.log(hd)
        //数组去重
        let array = [1,2,3,4,5,2,3,1,6]
        array = [...new Set(array)]
        console.log(array)
    </script>
</body>
</html>

遍历Set类型的方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let set = new Set(["hdcms","houdunren"])
        console.log(set.values())
        console.log(set.entries())
        [1,2,3].forEach(function(value,key,arr){
            console.log(value,key)
        })
    </script>
</body>
</html>

使用Set处理网站关键词

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            padding: 200px;
        }
        ul{
            list-style: none;
            padding: 0;
            margin: 0;
            width: 200px;
        }
        li{
            border: solid 1px #ddd;
            padding: 10px;
        }
        li:nth-of-type(odd){
            background: yellowgreen;
        }
    </style>
</head>
<body>
    <input type="text" name="hd" id="">
    <ul></ul>
    <script>
        let obj = {
            data: new Set(),
            set keyword(word){
                this.data.add(word)
            },
            show(){
                let ul = document.querySelector('ul')
                ul.innerHTML = ''
                this.data.forEach(function(value){
                    ul.innerHTML+=`<li>${value}</li>`
                })
            }   
        }
        let input = document.querySelector("[name='hd']")
        input.addEventListener('blur',function(){
            obj.keyword = this.value
            obj.show()
        })
    </script>
</body>
</html>

 


并集-交集-差集算法实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let a = new Set([1,2,3,4,5])
        let b = new Set([4,5,2,9])
        //并集
        console.log(new Set([...a,...b]))
        //差集
        console.log(new Set(
            [...a].filter(function(item){
                return !b.has(item)
            })
        ))
        //交集
        console.log(new Set(
            [...a].filter(function(item){
                return b.has(item)
            })
        ))
    </script>
</body>
</html>

WeakSet语法介绍

 WeakSet是一种集合类型,与 Set 类似,但它只能存储对象,不能存储原始数据类型

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let set = new WeakSet()
        // let set1 = new WeakSet(["hdcms","houdunren"]) 会报错
        set.add(["hdcms","houdunren"])  //不会报错
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div></div>
    <div></div>
    <script>
        let nodes = new WeakSet()
        let divs = document.querySelectorAll('div')
        divs.forEach(function(item){
            nodes.add(item)
        })
        console.log(nodes)
        nodes.delete(divs[0])
 </script>
</body>
</html>

引用类型的垃圾回收原理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let hd = {name:'后盾人'}
        let edu = hd    //被引用了两次
        hd = null     //引用计数-1
        edu = null     //没人用 -- 垃圾
        let arr = [hd]
    </script>
</body>
</html>

WeakSet弱引用特性

WeakSet有弱引用的特性,对循环的影响比较大

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>    
        let hd = {name:'后盾人'}
        let edu = hd    //被引用了两次
        let set = new WeakSet()
        set.add(hd)

        hd = null     //引用计数-1
        edu = null     //没人用 -- 垃圾
        console.log(set)    
    </script>
</body>
</html>

TODO任务列表中使用WeakSet 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
    </ul>
    <script>
        class Todo {
            constructor() {
                this.lists = new WeakSet();
                // 在 DOMContentLoaded 事件中执行操作,确保元素已经加载
                document.addEventListener('DOMContentLoaded', () => {
                    this.items = document.querySelectorAll("ul>li");
                    this.items.forEach(item => {
                        this.lists.add(item);
                    });
                    console.log(this.lists);
                    this.run();
                });
            }
            run() {
                this.addEvent();
            }
            addEvent() {
                this.items.forEach(item => {
                    const link = item.querySelector('a');
                    link.addEventListener('click', event => {
                        const parentElement = event.target.parentElement;
                        if (this.lists.has(parentElement)) {
                            parentElement.classList.add("remove");
                            this.lists.delete(parentElement);
                        } else {
                            alert("todo 已经删除了");
                        }
                    });
                });
            }
        }
        const todo = new Todo();
    </script>
</body>
</html>

没有添加样式,想要好看的话可以添加样式 


原文地址:https://blog.csdn.net/chestnut_orenge/article/details/145235346

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!