几种javascript数组方法的简单总结:
① concat();合并两个数组;
格式: newArray=OldArray.concat(new element);
<!DOCUMENT HTML>
<html>
<head>
<meta charset="utf-8">
<title>concat</title>
</head>
<body>
<script type="text/javascript">
varnums1=["green","red","gray"];
varnums2=["1","2","3"];
document.write(nums1+"<br/>");
document.write(nums2+"<br/>");
nums1=nums1.concat(nums2);
document.write(nums1);
</script>
</body>
</html>
输出结果:
green,red,gray
1,2,3
green,red,gray,1,2,3
② pop()方法删除并返回数组的最后一个元素
用法:varpoped=myArray.pop();
<!DOCUMENT HTML>
<html>
<head>
<meta charset="utf-8">
<title>pop()</title>
</head>
<body>
<script type="text/javascript">
var color=newArray("green","red","silver");
document.write(color+"<br/>");
var colordel=color.pop();
document.write(color+"<br/>");
document.write(colordel+"<br/>");
</script>
</body>
</html>
输出结果:
green,red,silver
green,red
silver
③ push()方法可在数组后添加新元素
用法:Arrayname.push(new elements);
<!DOCUMENT HTML>
<html>
<head>
<meta charset="utf-8">
<title>push()</title>
</head>
<body>
<scripttype="text/javascript">
varcolor=new Array("green","red","silver");
document.write(color+"<br/>");
color.push("black","blue");
document.write(color+"<br/>");
</script>
</body>
</html>
输出结果:
green,red,silver
green,red,silver,black,blue
④ shift()/unshift()
shift()方法的作用是移除头部的第一个元素,并且返回被删除的元素unshift()是往头部增加元素。
用法:var return_value=Myarray.shift();
MyArray.unshift(element1,element2….);
<!DOCUMENTHTML>
<html>
<head>
<meta charset="utf-8">
<title>shift/unshift</title>
</head>
<body>
<scripttype="text/javascript">
varcolor=new Array("green","red","silver");
document.write(color+"<br/>");
var return_color=color.shift();
document.write(color+"<br/>");
color.unshift("black","blue");
document.write(color+"<br/>");
</script>
</body>
</html>
输出结果:
green,red,silver
red,silver
black,blue,red,silver
⑤ slice()方法
slice()方法将数组元素复制到另一个新数组中,slice()方法有两个参数,第一个是复制的其实元素。第二个参数是复制终止元素,且不包括该索引元素。
⑥ splice()方法
splice()方法将从数组的某一位置开始移除指定数目的元素,并可以使用新元素代替这些元素。
<!DOCUMENT HTML>
<html>
<head>
<meta charset="utf-8">
<title>splice</title>
</head>
<body>
<scripttype="text/javascript">
varcolor=new Array("green","red","silver");
document.write(color+"<br/>");
color.splice(1,1,"blue","black");
document.write(color+"<br/>");
</script>
</body>
</html>
输出结果:
green,red,silver
green,blue,black,silver
欢迎各位朋友指正。