js数组和链表的区别

JavaScript022

js数组和链表的区别,第1张

唯一的区别是,数组的属性是0-n整数

对象的属性可以是任意字符串

比如有一个数组a=[1,2,3,4],还有一个对象a={0:1,1:2,2:3,3:4},然后你运行alert(a[1]),两种情况下的运行结果是相同的!这就是说,数据集合既可以用数组表示,也可以用对象表示,那么我到底该用哪一种呢?

数组表示有序数据的集合,而对象表示无序数据的集合。如果数据的顺序很重要,就用数组,否则就用对象。

当然,数组和对象的另一个区别是,数组的数据没有”名称”(name),对象的数据有”名称”(name)。

但是问题是,很多编程语言中,都有一种叫做”关联数组”(associative

array)的东西。这种数组中的数据是有名称的。

java数组的应用教程:

常规数组: 数组元素内容是一种类型的元素,如const arr = [1,2,3,4],在存储空间是连续内存的

JS数组: 数组元素内容不是同一种类型的元素,如const arr = ['haha', 1, {a:1}],则在存储上是一段非连续空间。此时,JS 数组不再具有数组的特征,其底层其实是由链表来实现的

总结

链表的插入/删除效率较高,而访问效率较低;

数组的访问效率较高,而插入效率较低

//Node表示要加入列表的项

var Node=function(element){

this.element=element

this.next=null

}

var length=0//存储列表项的数量

var head=null//head存储的是第一个节点的引用

//向链表尾部追加元素

this.append=function(element){

var node=new Node(element),

current

if(head===null){

head=node

 }else{

current=node

while(current.next){

current=current.next

}

current.next=node

}

length++

}

//在链表的任意位置插入元素

this.insert=function(position,element){

if(position>=0&&position<=length){

var node=new Node(element),

current=head,

previous,

index=0

if(position===0){

node.next=current

head=node

}else{

while(index<position){

previous=current

previous.next=node

index++

}

node.next=current

previous.next=node

}

length++

return true

}else{

return false

}

}

//从链表中移除元素

this.removeAt=function(position){

if(position>-1 && position<length){

var current=head,

previous,

index=0

if(position===0){

head=current.next

}else{

while(index<position){

previous=current

current=current.next

index++

}

previous.next=current.next

}

length--

return current.element

}else{

return null

}

}

//返回元素在链表中的位置

this.indexOf=function(element){

var current=head,

index=-1

while(current){

if(element===current.element){

return index

}

index++

current=current.next

}

return -1

}

//移除某个元素

this.remove=function(element){

var index=this.indexOf(element)

return this.removeAt(index)

}

//判断链表是否为空

this.isEmpty=function(){

return length===0

}

//返回链表的长度

this.size=function(){

return length

}

//把LinkedList对象转换成一个字符串

this.toString=function(){

var current=head,

string=""

while(current){

string=current.element

current=current.next

}

return string

}

}

var list=new LinkedList()

list.append(15)

list.append(10)

list.insert(1,11)

list.removeAt(2)

console.log(list.size())