目录
②a.forEach(function(遍历的元素,索引,此数组对象){}) 用function的匿名函数作为参数
④map将数组里面的子元素转换成number或者string
2.array.includes(searcElement,[fromIndex]) 可以传两个参数,第一个是要查找的元素,第二个是查找的起始位置
3.array.find(item => {return } )
4.array.findeIndex(callback[,thisArg])
① 用数组ES6新增的 .flat(Infinity) 方法
一:数组循环
①for循环遍历
②a.forEach(function(遍历的元素,索引,此数组对象){}) 用function的匿名函数作为参数
forEach 不能用 break 或者 return
③ 数组循环的比较
- forEach改变元素组
- filter在元素组的基础上生成一个新数组
- every 和 some 做判断
- map 生成一个新数组
④map将数组里面的子元素转换成number或者string
<script>
var arr = ['1','2','3']
let newArr1 = arr.map(Number) //[1,2,3]
let newArr2 = newArr1.map(String) //['1','2','3']
console.log(newArr1);
console.log(newArr2);
</script>
二:判断数组是否包含某个值
1.array.indexOf
- 判断数组中是否存在某个值,如果存在,则返回数组元素的下标,否则返回-1。
<script>
var arr = [1,2,6,8,9]
console.log(arr.indexOf(2)) //1
</script>
2.array.includes(searcElement,[fromIndex]) 可以传两个参数,第一个是要查找的元素,第二个是查找的起始位置
- 判断数组中是否存在某个值,如果存在返回true,否则返回false
<script>
var arr = [1,2,6,8,9]
console.log(arr.includes(2)) //true
</script>
3.array.find(item => {return } )
- 返回数组中满足条件的第一个元素的值,如果没有,返回undefined
<script>
var arr = [1,2,6,8,9]
var res = arr.find(item =>{
return item>6
})
console.log(res) //8
</script>
4.array.findeIndex(callback[,thisArg])
- 返回数组中满足条件的第一个元素的下标,如果没有找到,返回 -1
<script>
var arr = [1,2,6,8,9]
var res = arr.findIndex(item =>{
return item>6
})
console.log(res) //3
</script>
三:数组扁平化
- 对于前端项目开发过程中,偶尔会出现层叠数据结构的数组,我们需要将多层级数组转化为一级数组(即提取嵌套数组元素最终合并为一个数组),使其内容合并且展开。那么该如何去实现呢?
需求:多维数组=>一维数组
[1,[1,[8,9,9,[2]],8,3],2] => [1, 1, 8, 9, 9, 2, 8, 3, 2]
① 用数组ES6新增的 .flat(Infinity) 方法
<script>
var x = [1,[1,[8,9,9,[2]],8,3],2]
console.log(x.flat(Infinity)) //Infinity任意深度,不加Infinity代表只拆解第一层
</script>
②replace + split
- 先用 JSON.stringify转换成字符串类型,
- 再用replace将所有的 [ 和 ] 替换成空
- 再以逗号分割成数组
<script>
let x = [1,[1,[8,9,9,[2]],8,3],2]
let str = JSON.stringify(x); // 先转换成字符串类型
x = str.replace(/(\[|\])/g, '').split(',') //[1, 1, 8, 9, 9, 2, 8, 3, 2]
console.log(x)
</script>
③replace + JSON.parse
-
先将数组用JSON.stringify转换为字符串
-
再用replace将 [ 和 ] 以 空 替代
-
再在这行字符串两边加上 [ 和 ]
-
再用 JSON.parse 转换成新数组
<script>
let x = [1,[1,[8,9,9,[2]],8,3],2]
let str = JSON.stringify(x); // 先转换成字符串类型 [1,[1,[8,9,9,[2]],8,3],2]
str = str.replace(/(\[|\])/g, '') // 1,1,8,9,9,2,8,3,2
str = '[' + str + ']' // [1,1,8,9,9,2,8,3,2]
x = JSON.parse(str) // [1, 1, 8, 9, 9, 2, 8, 3, 2]
console.log(x)
</script>
④普通递归
<script>
// 数组的扁平化(将多维数组转换成一维数组)
var x = [1,[1,[8,9,9,[2]],8,3],2]
let newX = []
function fn(x){ //[1,2,3]
x.forEach(item => {
if(Array.isArray(item)){
fn(item)
}else{
newX.push(item)
}
})
}
fn(x)
console.log(newX) //[1, 1, 8, 9, 9, 2, 8, 3, 2]
</script>