3.3数组的遍历方式;3.4数组的常用方法
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
var arr=[5,7,3,1,6,2,4,9,8];
/*
* 普通for循环遍历数组
* */
for(var i=0;i<arr.length;i++){
console.log(arr[i])
}
/*
*foreach循环遍历数组
* JS 中foreach写法为 for( var i in 数组)
* i 不是元素 是索引
* */
for (var i in arr){
console.log(arr[i])
}
</script>
</head>
<body>
</body>
</html>
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
![点击并拖拽以移动](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
数组的常用方法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
var arr=[1,2,3,4,5,6,7,8,9];
var index =arr.indexOf(7);//查询元素索引的方法
console.log(index)
// 合并两个数组
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
console.log(children)
// 合并三个数组
var parents = ["Jani", "Tove"];
var brothers = ["Stale", "Kai Jim", "Borge"];
var children = ["Cecilie", "Lone"];
var family = parents.concat(brothers, children);
console.log(family)
// 合并字符串
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fs =fruits.join();
console.log(fs)
// 移除最后一个元素
var fruit=fruits.pop();
console.log(fruits)
console.log(fruit)
// 想结尾增加元素
fruits.push("Grape");
console.log(fruits)
//反转数组
fruits.reverse();
console.log(fruits)
//删除数组第一个元素
var ss =fruits.shift();
console.log(fruits);
console.log(ss)
//向第一个位置添加元素
fruits.unshift("火龙果");
console.log(fruits);
// 截取子数组 从哪个索引开始,到哪个索引结束 包头不包尾
var citrus = fruits.slice(1,3);
console.log(citrus)
var numbers =[1,2,3,4,5,6,7,8,9]
/*
* 删除数组中的某些元素
* 2 从哪个索引开始删除
* 3 删除多个少个元素
* */
/*numbers.splice(2,3);
console.log(numbers)*/
/*
* 如果第二个参数是0 那么就变成了在指定索引位置增加元素
* */
numbers.splice(2,0,100);
console.log(numbers)
</script>
</head>
<body>
</body>
</html>
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
![点击并拖拽以移动](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
数组元素的排序
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits)
var numbers=[5,7,9,6,1,8,3,4,2];
numbers.sort(function(a,b){return b-a});
console.log(numbers)
</script>
</head>
<body>
</body>
</html>
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)
![点击并拖拽以移动](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108211712009-1593085570.gif)