链表
指针指向,js中的obj的存储方式就是这种类似的指向地址。
const a = {val: 'a'} const b = {val: 'b'} const c = {val: 'c'} const d = {val: 'd'} //Obj模拟链表 a.next=b b.next=c c.next=d //遍历链表 let p =a ;//申明指针 while (p){ console.log(p.val) p=p.next } //插入值 const e = {val :'e'}; c.next=e; e.next=d; //删除 c.next =d ;//改变指向
原型链就是js中的链表
*原型链的本质是链表
*原型链上的节点是各种原型对象,function.prototype.object.prototypy..
*原型链通过__proto__属性链接各种原型对象。
原型链样子?
obj - > Object.prototypy - > null
func - > Function.prototype - > Object.prototype - > null
arr - > Array.prototype - > Object.prototype - > null
原型链知识点
如果A沿着原型链能找到B.prototype ,那么A instanceof B 位 true //A为B的实例
如果在A对象上没有找到x属性,那么会沿着原型链找x属性
const obj={} const func=()=>{} const arr=[] obj.__proto__===Object.prototype obj instanceof Object//true func instanceof Object//true arr instanceof Object//true obj.x//undefined Object.prototype.x='x' obj.x//x Function.prototype.y='y' func.y//y
//instacnceof的原理,用代码实现 const instanceOf=(A,B)=>{ let p=A while (p){ if(p===B.prototype){ return true } p=p.__proto__; } return false }
//输出什么 var foo={}, F=function (){} Object.prototype.a='value a' Function.prototype.b='value b' console.log(foo.a)//value a console.log(foo.b)//undefind console.log(F.a)//value a console.log(F.b)//value b
json与链表
const json={ a:{b:{c:1}}, d:{e:2} } const path=['a','b','c'] let p =json path.forEach(k=>{ p=p[k] }) //p=1
技术要点
*链表里的元素存储不是连续的之间通过next连接
*js中没有链表,但可以用Object模拟链表
*链表常用操作:修改next、遍历链表
***js中的原型链也是一个链表
***使用链表指针可以获取JSON的节点值