javascript 原型链
graph TB
A[对象]--->B[原型]
对象的创建
-
使用json创建
var obj = { name:"", age:"" }
-
使用工厂函数创建
function createobj(){ var obj = new Object(); obj.name = "", obj.age = "" }
-
构造函数
使用js实现单向链表
<script>
// 使用js实现链表
function Link() {
this.head;
this.size = 0;
// 链表里面的节点
function Node() {
this.next;
this.data;
}
// 添加头结点
this.addhead = function(data) {
let n = new Node();
n.data = data;
if (this.size == 0) {
this.head = n;
n.next = null;
} else {
n.next = this.head;
this.head = n;
}
this.size++;
}
// 获取第几个节点
this.getdata = function (a){
let data = this.head;
for(let i=1;i<a;i++){
data = data.next;
}
return data;
}
// 添加尾结点
this.addtail = function(data){
let n = new Node();
n.data = data;
if(this.size == 0){
this.head = n;
n.next = null;
}else{
this.getdata(this.size).next = n;
n.next = null;
}
this.size++;
}
// 删除尾结点
this.removetail = function(){
// 获取最后一个节点的前一个节点,让前一个节点指向空
this.getdata(this.size-1).next=null;
this.size--;
}
// 删除头结点
this.removehead = function(){
this.head = this.head.next;
this.size--;
}
}
let link = new Link();
link.addhead("ni");
link.addhead("wo");
link.addhead("ta");
link.addtail("付立翔");
// console.log(link.head.next);
</scrip>
Js实现栈
<script>
// 实现栈
function zhan(){
this.head;
this.size = 0;
function Node(){
this.data;
this.next;
}
this.add = function(data){
let n = new Node();
n.data = data;
if(this.size == 0){
this.head = n;
n.next = null;
}else{
n.next = this.head;
this.head = n;
}
this.size++;
}
this.tan = function(){
let he = this.head;
this.head = this.head.next;
return he;
}
}
</script>