当前位置: 首页 > article >正文

后盾人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>

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


http://www.kler.cn/a/513715.html

相关文章:

  • 【JVM-9】Java性能调优利器:jmap工具使用指南与应用案例
  • 68,[8] BUUCTF WEB [RoarCTF 2019]Simple Upload(未写完)
  • 【Day23 LeetCode】贪心算法题
  • SDL2:PC端编译使用 -- SDL2多媒体库使用音频实例
  • 美区TikTok解封后如何回归使用?
  • SpringCloud nacos 2.0.0 + seata 2.0.0
  • 《鸿蒙Next原生应用的独特用户体验之旅》
  • PyCharm+RobotFramework框架实现UDS自动化测试- (四)项目实战0x10
  • UDP/TCP ②-三次握手 || 四次挥手 || 确认应答 || 超时重传
  • Single-Model and Any-Modality for Video Object Tracking——2024——cvpr-阅读笔记
  • 深入解析迁移学习:Transfer Learning模型介绍
  • Spring AI SafeGuardAdvisor
  • JSqlParser:Java SQL 解析利器
  • Codeforces Round 998 (Div. 3)(部分题解)
  • sql:权限管理、存储过程、视图、触发器
  • 从零搭建一套远程手机的桌面操控和文件传输的小工具
  • 小土堆学习笔记10(利用GPU训练于模型验证)
  • 【论文复现】基于改进鲸鱼优化算法的太阳能光伏模型参数提取问题
  • 嵌入式Linux驱动开发之从设备树到点亮LED
  • 使用 Python 获取淘宝商品描述的 API 接口实现与应用
  • C# 委托和事件(事件)
  • 如何用vscode断点调试Vue.js的项目
  • 在亚马逊云科技上用AI提示词优化功能写出漂亮提示词(上)
  • 解决windows系统远程桌面(或其他全屏应用)全屏后菜单栏不自动消失问题
  • Python多态的概念
  • R语言基础| 回归分析