JS中如何让数组保持一定数据而可以更新新的数据。懂的进

JavaScript011

JS中如何让数组保持一定数据而可以更新新的数据。懂的进,第1张

似乎不太好解决,B数据中需存下当前时间.

<html>

<head>

<title>JS OBJECT STUDY</title>

<script>

//保持数组长度为10,当放第十一个元素的时候,原数组中的最老元素将被取代

function MyArray(){

this.array=new Array()//存放元素

this.pushTime=new Array()//存放时间

}

MyArray.prototype.push=function(obj){

var ctime=new Date().getTime()

if(this.array.length>=10){

//拷贝数组

var pt=this.pushTime.concat("")

//对数组排序

pt.sort()

var index=0

//寻找最老元素的下标

for(var i=0i<this.pushTime.lengthi++){

if(this.pushTime[i]==pt[0]){

index=i

break

}

}

//将最老元素替换

this.array.splice(index,1,obj)

this.pushTime.splice(index,1,ctime)

}else{

this.array.push(obj)

this.pushTime.push(ctime)

}

}

MyArray.prototype.pop=function(){

this.pushTime.pop()

return this.array.pop()

}

var a=new MyArray()

a.push("I")

a.push("love")

a.push("you")

a.push(",")

a.push("gao")

a.push("yuan")

a.push("hong")

a.push("ceng")

a.push("jing")

a.push("!")

a.push("ly")

alert(a.array)

alert(a.pop())

</script>

</head>

<body>

</body>

</html>

js中的var是定义变量的意思,使用和不使用var都能定义变量,但是两个变量的作用域不同。

1、新建html文档,在body标签中添加script标签,使用var定义一个变量a并给变量赋值为10,将a在控制台输出,这时控制台会输出10:

2、定义一个demo函数,在函数里面重新使用var定义一个变量a,由于函数外的变量a是全局变量,函数内的变量a是局部变量,所以在函数执行后,第一个输出是未赋值的局部变量a,第二个是赋值为5后的局部变量a,第三个是赋值为10的全局变量a:

3、将var去掉,直接定义变量a,这时js默认定义的a是全局变量,函数外和函数内共用一个变量a,所以变量数值正常输出: