一、数组定义
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组定义</title>
<script type="text/javascript">
//var arr=[1,2,3,4];
var arr=new Array(1,2,3,4);
alert(arr[0]);
alert(arr.length);
alert(arr);
</script>
</head>
<body>
</body>
</html>
二、数组连接concat
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串连接</title>
<script type="text/javascript">
/*
var str1='abc';
var str2='123';
alert(str1+str2);
*/
var arr1=[1,2,3];
var arr2=[6,7,8];
alert(arr1.concat(arr2));//输出1,2,3,6,7,8
</script>
</head>
<body>
</body>
</html>
三、快速清空数组
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组定义</title>
<script type="text/javascript">
//var arr=[1,2,3,4];
var arr=new Array(1,2,3,4);
arr.length=0;
alert(arr);//没有输出
</script>
</head>
<body>
</body>
</html>
四、将字符串变为数组split
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组split</title>
<script type="text/javascript">
var str='12-4-5-8';
var arr=str.split('-');
alert(arr[0]);//弹出12
</script>
</head>
<body>
</body>
</html>
五、将数组变为字符串join
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组join</title>
<script type="text/javascript">
var arr=[1,2,3,4];
alert(arr.join('-'));//弹出1-2-3-4
</script>
</head>
<body>
</body>
</html>
六、splice
删除: splice(开始,长度)
插入:splice(开始,0,元素)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组splice</title>
<script type="text/javascript">
/* 1.从数组的中间删除元素
var arr=[1,2,3,4,5,6,7,8];
arr.splice(2,3);
alert(arr);//输出1,2,6,7,8
*/
/* 2.从中间插入元素
var arr=[1,2,3,4,5,6,7,8];
arr.splice(5,0,'a','b','c');
alert(arr);//输出1,2,3,4,5,a,b,c,6,7,8
*/
//替换
var arr=[1,2,3,4,5,6,7,8];
arr.splice(1,2,'a','b');//输出1,a,b,4,5,6,7,8
alert(arr);
</script>
</head>
<body>
</body>
</html>
七、排序sort
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组定义</title>
<script type="text/javascript">
//var arr=['float','zindex','xy','absolute','blue','leo'];
var arr=[96,8,12,72,33,118];
arr.sort(function(num1,num2){
return num2-num1;
});
alert(arr);//118,96,72,33,12,8
</script>
</head>
<body>
</body>
</html>
八、数组添加
push(元素):从尾部添加
unshift(元素):从头部添加
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组定义</title>
<script type="text/javascript">
var arr=[1,2,3,4];
arr.push(4);
alert(arr);//弹出1,2,3,4,4
</script>
</head>
<body>
</body>
</html>
九、数组删除
pop():从尾部弹出
shift():从头部弹出
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组定义</title>
<script type="text/javascript">
var arr=[1,2,3,4];
arr.shift();
alert(arr);//弹出2,3,4
</script>
</head>
<body>
</body>
</html>