javascript - js链表的理解

查看:104
本文介绍了javascript - js链表的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

      function LinkedList() {
            let Node = function (ele) {
                this.ele = ele
                this.next = null
            },
                length = 0, head = null;
            this.append = function (ele) {
                var node = new Node(ele), //{1}         
                    current; //{2} 
                if (head === null) { //列表中第一个节点 //{3}         
                    head = node;
                } else {
                    current = head; //{4} 
                    //循环列表,直到找到最后一项         
                    while (current.next) {
                        current = current.next;
                    }
                    //找到最后一项,将其next赋为node,建立链接         
                    current.next = node; //{5}     
                }
                length++; //更新列表的长度 //{6} 
            };
           this.print = function () {
            var current = head, //{1}         
                string = '';    //{2} 

            while (current) {   //{3}         
                string += current.ele; //{4}         
                current = current.next;   //{5}     
            }
            return string;                //{6} 
        };
    }
    let LinkedList1= new LinkedList();
    [1,2,3,4,5,6].forEach(function (value) {
        LinkedList1.append(value)
    })
    console.log(LinkedList1.print(); //123456

这样实现一个链表的话,每一个项存在哪个函数的作用域?如果是append这个函数的作用域,print查找的时候非父级作用域的变量可以读取吗?

解决方案

所有的项都存在head中,也就是LinkedList这个闭包中

此处验证也比较简单,我们在chrome的调试工具中打断点,可以看到是在闭包中的

这篇关于javascript - js链表的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆