在使用js中,如何使用数组?
如何声明一个数组?
var students=new Array();
var students=[];
常用的方法有哪些?
push()
unshift()
shift() //从前边删除一个值
pop() //从后边删除
slice(start[,end]); //截取字符
concat(item1,item2) //在数组中添加上item1和item2这两个元素
reverse() //数组反转
<html>
<head>
<meta charset="utf-8">
<title>我的文件 js</title>
<script typet="text/javascript">
window.onload=function(){
var a=[1,3,4,5,6];
console.log("length:"+a.length); //length:5
console.log("数组a的值:"+a);//test.html:13 数组a的值:1,3,4,5,6
a.push("song"); //添加一个元素 放在最后一位
console.log("数组a的值:"+a);//test.html:17 数组a的值:1,3,4,5,6,song
a.unshift("james"); //添加一个元素放在最后一位
console.log("数组a的值:"+a);//test.html:20 数组a的值:james,1,3,4,5,6,song
a=a.concat("user",5,"address"); //应该返回一个新数组
console.log("数组a的值:"+a); //test.html:23 数组a的值:james,1,3,4,5,6,song,user,address
console.log("数组a的值:"+a.unique());
//a=a.slice(7);
//console.log(a); //以数组的形式返回数组的一部分,注意不包括 end 对应的元素,如果省略 end 将复制 start 之后的所有元素
//a.shift(); //删除第一个
//console.log("数组a的值:"+a);
//a.pop(); //删除最后一个
//console.log("数组a的值:"+a);
document.body.innerHTML=a.join(" , ");
}
Array.prototype.unique=function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
Array.prototype.unique2=function(){
this.sort(); //先排序
var res = [this[0]];
for(var i = 1; i < this.length; i++){
if(this[i] !== res[res.length - 1]){
res.push(this[i]);
}
}
return res;
}
</script>
</head>
<body>
</body>
</html>