前端之数据结构(二)

这是我参与8月更文挑战的第三天,活动详情查看:8月更文挑战数组

直接书接上回。markdown

数据结构

数据结构:计算机存储、组织数据的方式,就像锅碗瓢盆。数据结构

链表

  • 多个元素组成的列表。
  • 元素存储不连续,用 next 指针连载一块儿。

image.png

那为啥不用数组呢?

  • 数组:增删非首尾元素每每须要移动元素。app

  • 链表:增删非首尾元素,不须要移动元素,只须要更改 next的指针便可。post

  • JavaScript中是没有链表的,可是能够用 Object模拟链表。ui

经过以下代码,咱们就能够建造一个简易的链表:url

const a = {val: 1}
const b = {val: 2}
const c = {val: 3}
const d = {val: 4}

a.next = b
b.next = c
c.next = d
复制代码

结构以下:spa

image.png

那怎么遍历链表呢?

let p = a;
while (p) {
    console.log(p.val);
    p = p.next
}

// 1
// 2
// 3
// 4
复制代码

那插入链表呢?

很简单。prototype

const e = { val: '5'}
c.next = e
e.next = d
复制代码

image.png

这时候咱们就能看到插入的数据了。3d

还有删除呢?

更简单了。

c.next = d
复制代码

image.png

看,已经删除完了。

原型链与链表

  • 原型链的本质就是链表。

  • 原型链 上的结点是各类原型对象,好比 Object.prototype, FUnction.prototype

  • 原型链经过 __proto__属性连接各类原型对象,而链表经过 next 连接。

那原型链长啥样呢?

image.png

咱们能够发现,funcarr 是指向本身的原型链对象,在指向 Obj 的原型链对象。

咱们能够经过以下代码,验证一下原型链:

const arr = new Array()
const fun = () => {}
const Obj = new Object()
复制代码
  • 若是 A 沿着原型链能找到 B.prototype, 那么 A instanceOf Btrue

  • 同上,遍历原型链和遍历链表同样,

const instanceOf = (A, B) => {
    let p = A
    while (p) {
        if (p === B.prototype) {
            return true
        }
        p = p.prototype
    }
    return false
}
复制代码

end~~~

相关文章
相关标签/搜索