数组循环 ES5新增方法 悠悠 2022-02-20 17:51 291阅读 0赞 1. arr.forEach() // 代替for 循环 let arr = ['1','2','3','4','5']; arr.forEach(function(val,index,arr){ console.log(val,index,arr); }); 2. arr.map() //做数据交互,映射 正常情况下,需要配合return,返回一个新的数组,若没有相当于forEach。 注意:平时用map,一定要用return let arr = [ {title:'aaa',read:'100',hot:true}, {title:'bbb',read:'200',hot:true}, {title:'ccc',read:'300',hot:true}, {title:'ddd',read:'400',hot:true} ]; let arr1=arr.map((item,index,arr)=>{ let json={}; json.t=`你好${item.title}`; json.r=item.read; return json; }); console.log(arr1) 3. arr.filter() //过滤 过滤一些不合格'' 元素 '',如果回调函数返回的是true 就留下来 let arr = [ {title:'aaa',read:'100',hot:true}, {title:'bbb',read:'200',hot:false}, {title:'ccc',read:'300',hot:true}, {title:'ddd',read:'400',hot:false} ]; let arr1=arr.filter((item,index,arr)=>{ return item.read==100; }); console.log(arr1) 4. arr.some() //类似查找 返回true 和 false 数组里面某一个元素符合条件,返回true 5. arr.every() //查找 数组里面所有的元素符合条件,返回true **arr.forEach/map/filter/some/every (循环回调函数,this指向谁) //有两个参数** **也可以用箭头函数,但是this指向会受箭头影响** 6. arr.reduce() // reduce减少 从左往右 求数组的和、阶乘 let arr=[2,2,3]; let res= arr.reduce((prev,cur,index,arr)=>{ return Math.pow(prev.cur) // // 幂运算符 //2**3 }) console.log(res); 7. arr.reduceRight() 从右往左 ES6 的 for...of... 循环 let arr = ['a','b','c']; for(let val of arr){ console.log(val) } for(let index of arr.keys()){ console.log(index) } for(let item of arr.entries()){ console.log(item) } for(let [key,val] of arr.entries()){ console.log(key,val) } 数组操作 1.arr.find() 查找 找出第一个符合条件的数组成员 ,如果没有找到,返回undefinded let arr=[1,2,34,5,63]; let res-arr.find((val,index.arr)=>{ return val >2 }) console.log(res) //找到的只是第一个满足条件的元素 arr.findIndex() 找位置 没有找到返回 -1 2Array.of() 把一组值,转成数组 let arr = Array.of('1','3','6'); 3.Array.from() 作用:把类数组(获取一组元素、arguments。。。)对象转成数组 具有length就靠谱 let json={ 0:'a', 1:'b', 2:'c', length:2 } let arr=Array.from(json) 4.arr.fill() 填充 arr.fill(填充的东西,开始的位置,结束的位置) ES6新增 arr.includes() 包含 arr.indexOf()
还没有评论,来说两句吧...