var arr1 = [1,2,3,4,5,6];
arr1[0];
arr1[1];
console.log("长度:"+arr1.length);
一、遍历数组
/ * i=下标*/
for(var i=0;i<arr1.length;i++){
console.log(arr1[i]);
}
/*循环添加内容*/
var arr2 = new Array(6);
for(var i=0;i<arr2.length;i++){
arr2[i] = prompt("请输入成绩");
}
console.log(arr2);
/*添加数据的第二种办法: push()*/ var arr3 = new Array(1,2,3); arr3.push("a","b"); //默认添加至数组的最后 arr3.push("c"); console.log(arr3); //1,2,3,a,b,c 二、删除数据/*1. 删除第一条数据: shift()*/ var arr4 = ["a","b","c","d","e","f"]; arr4.shift(); /*2.删除最后一条数据: pop()*/ arr4.pop(); console.log(arr4.length); console.log(arr4[4]); /*3.删除中间某一条数据: splice(起始下标,删除多少项)*/ arr4.splice(2,1); console.log(arr4); console.log(arr4.length);//当发生删除之后,数组长度会发生改变 console.log(arr4[4]); 三、替换数据
/*替换数据 : splice(起始下标,删除多少项,替换的新数据)*/ var arr5 = ["a","b","c","d","e","f"]; arr5.splice(1,3,"bbbb"); console.log(arr5); 四、插入数据 /*插入数据: splice(起始下标,删除多少项,替换的新数据)*/ arr5.splice(1,0,"bbbbbb"); console.log(arr5);//["a", "bbbbbb", "b", "c", "d", "e", "f"] 五、数组合并/*数组合并: concat()*/
var arr6 = [1,2,3]; var arr7 = [4,5,6]; var newarr = arr6.concat(arr7); //返回一个合并了的新数组 var newarr = arr6.concat("a","b"); //返回一个合并了的新数组 console.log(arr6); console.log(arr7); console.log(newarr); 六、数组抽取 /*数组抽取: slice(起始下标,结束下标不包含自己)*/ var arr8 = [1,2,3,4,5,6]; var newarr2 = arr8.slice(2,-1); /*通过返回一个slice后的新数组 负数代表从最后开始倒数*/ console.log(arr8); console.log(newarr2); 七、数组排序 /*数组排序*/ var arr9 = [3,2,1,6,4,7,5]; var arr10 = arr9; var arr10 = []; /*Array复制的方法*/ for(var i=0; i<arr9.length;i++){ arr10[i]=arr9[i]; } arr9.sort(); //从小到大进行排序 console.log(arr9); console.log(arr10); /*数组串联: join("串起来的符号")*/ var arr11 = [1,2,3,4,5,6]; var newarr3 = arr11.join("+"); console.log(arr11); console.log(newarr3); //把所有数组内的数据通过制定符号串联起来
时间: 2024-11-17 13:19:58