<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<script>
//1使用直接量创建数组arr1
let arr1=[1,2,3,4,'hello',true];
document.write("arr1="+arr1+"<br>");
//2使用Array构造函数创建数组arr1
let arr2 = new Array(11,2,33,4,12,21);
document.write("arr2="+arr2+"<br>");
//3输出arr1和arr2数组元素的个数
document.write("arr1的元素有"+arr1.length+"个<br>");
document.write("arr2的元素有"+arr2.length+"个<br>");
//4在arr1中的下标为8的位置添加元素8
arr1[8]=8;
document.write("添加元素后:arr1="+arr1+"<br>");
//5将arr1和arr2中的每个元素+1后输出
for(i in arr1){
arr1[i]++;
document.write(arr1[i]+" ");
}
document.write("<br>");
for(i in arr2){
arr2[i]++;
document.write(arr2[i]+" ");
}
document.write("<br>");
//6构造数组的方法,计算数组元素的和
Array.prototype.sum=function(){
var sum=0;
for(x of this){
sum+=x;
}
return sum;
}
document.write(arr2.sum());
document.write("<br>");
//7将b数组从大到小排序
let b=[4284,48468,48,1321,5,458];
function cmp(x,y){//cmp函数
return y-x;//这里不能用x<y
}
b.sort(cmp);
document.write(b);
document.write("<br>");
//8删除arr1中的hello元素
arr1=[1,2,3,4,'hello',true];
for(i=0;i<arr1.length;i++){
if(arr1[i]=='hello')delete arr1[i];
}
document.write(arr1+"<br>");
//9使用prototype给数组添加属性name,name的属性为arr
Array.prototype.name='arr';
document.write("arr1的name属性:"+arr1.name+"<br>");
document.write("arr2的name属性:"+arr2.name+"<br>");
//10使用join方法将arr1中的元素连接成字符串
let str=arr1.join('-');
document.write(str+"<br>arr1的类型为:"+typeof arr1+"<br>str的类型为:"+typeof str);
//11将arr2中的元素逆序
arr2.reverse();
document.write("arr2逆置后:arr2="+arr2+"<br>");
//12给arr2中的元素排序
arr2.sort();
document.write("arr2默认排序后:arr2="+arr2+"<br>");
function cmp(a1,a2){
return a1-a2;//从小到大
}
arr2.sort(cmp);
document.write("arr2使用回调函数排序后:arr2="+arr2+"<br>");
//13将arr2数组中原来下标为1到3(不包含3)的位置用元素8,7,6,5,元素值来替换。
arr2.splice(1,2,8,7,6,5);
document.write("arr2被替换后:arr2="+arr2+"<br>");
//14截取arr2数组下标1到3(不包含3)的位置的元素值。
let subArr2=arr2.slice(1,3);
document.write("arr2的子数组:subArr2="+subArr2+"<br>");
document.write("arr2="+arr2+"<br>");//被截取了原数组会损失
//15在arr2数组的最后插入元素88,用栈
arr2.push(88);
document.write("在最后插入88后:arr2="+arr2+"<br>");
//16在arr2数组的最前面插入元素99
arr2.unshift(99);
document.write("在最前面插入99后:arr2="+arr2+"<br>");
//17将arr1和arr2合并后生成新的数组arr3
let arr3=arr1.concat(arr2);
document.write("arr1和arr2合并后:arr3="+arr3+"<br>");
</script>
</body>
</html>