第四章:数组
1.什么是数组
数组:一堆数的组合。
================
之前的变量都是单个单个的,一个学生成绩,学生姓名,手机号码
但是我们经常要描述一堆。比如,一个班里30个学生成绩。
s1,s2,s3...s30 变量么
=====
不科学的,所以,就需要一种数据类型,数组
js里的数组,功能是非常强大的。可变长度。长度不固定,不够用了,自动会扩容。数组里可以存放任意数据类型
2.定义和访问数组
<script type="text/javascript">
var arr=new Array();
arr[0]=10;
arr[1]=20;
arr[2]="abc";
arr[-1]=99;
console.log(arr[0],arr[1],arr[2],arr[100],arr[-1]);
var arr2=[1,2,3,4,5];
console.log(arr2[0],arr2)
script>
3.数组的遍历
<script type="text/javascript">
var arr=["aa","bb","cc","dd","ee"];
console.log("使用索引方式遍历:")
for(let i=0;i<arr.length;i++){
console.log(arr[i]);
}
console.log("使用增强for 方式遍历:");
for (let i in arr) {
console.log(arr[i]);
}
console.log("使用for ..of方式遍历,ES6");
for (let item of arr) {
console.log(item);
}
script>
4.数组常用方法
<script type="text/javascript">
var arr=[1,2,3];
arr.push(4);
console.log(arr);
let x1=arr.pop();
console.log(x1,arr.join(","));
arr.unshift(10,20);
console.log(arr.join(","));
x1=arr.shift();
console.log(x1,arr.join(","));
arr.push(6,7,8,9);
console.log("删除前",arr);
arr.splice(2,3)
console.log("删除后",arr);
arr.splice(2,3,50,60,70,80)
console.log("删除后插入:",arr);
arr.splice(4,0,999)
console.log("插入后:",arr);
arr=[1,2,3,4,5,6,7,8,9,10]
arr2=arr.slice(3,6);
arr2[1]=99;
console.log(arr2.join(","),"原数组:",arr.join(","))
arr2=arr.slice(3);
console.log(arr2);
arr1=[1,2,3,4];
arr2=[7,8,2];
arr3=arr1.concat(arr2);
console.log(arr3)
script>
5.二维数组
多维数组,js中不存在多维数组,都是一维数组。
如果数组里的每一个元素都是一个一维数组。就是二维
<script type="text/javascript">
const books=[
[1,"java基础",20],
[2,"js基础",10],
[3,"c++基础",30],
[4,"go基础",20],
[5,"python基础",40],
];
let html="";
html+="";
html+="编号 | 书名 | 单价 | ";
html+="
";
for (let book of books) {
html+=""
html+=""+book[0]+" | ";
html+=""+book[1]+" | ";
html+=""+book[2]+" | ";
html+="
";
}
html+="
";
document.write(html);
script>