ES6 数组方法

ES6 以下是个人对ES6 数组方法的理解和学习 map() map方法 是数组的遍历方法 类似于JQ的foreach() JS 的for循环 遍历。 map方法: 调用map时,会生成一个新的数组,需要传入一个回调函数,新数组的内容,取决于该回调函数的返回值 用法 : var arr = ["小明","小红","小兰"] //这里我把arr 进行遍历,重新构造成 数组嵌套对象的结构 let newArr = arr.map(item=> {name:item} ); // newArr 输出后的数组为 [{name:'小明'},{name:'小红'},{name:'小兰'}] 你或许看不懂,那我们可以这样换一下 var arr = ["小明","小红","小兰"] arr.map(function(item,index){ return { name: item} }); // 一样的结果 [{name:'小明'},{name:'小红'},{name:'小兰'}] filter() filter方法 生成一个新的数组,数组的内容,取决于 回调函数中的 返回值, 返回true 就会被添加进去数组,如果返回false,则不会添加进去数组 filter( (item,index) => {} ) const arr = [1,2,3,4,5]; const newArray = arr.filter( item => item >1 ) console.log(newArray) [2,3,4,5] forOf遍历方法 ​ 用于快速遍历数组中的每一个元素; ​ 可以用来遍历字符串(遍历出来的字符串会拆分成单个单个的形式输出) 遍历出来的值, 是对应的项的值,而不是index索引 ​ const colors = ['red','blue','green']; for(let color of colors) { console.log(color); } //输出结果为 red blue green; 额外用法:可用于 const lis = document.querySelectorAll('li'); for(let li of lis) { li.onclick = function(){}; } Array.from() Array.from( item,fn )方法主要用于:将类数组和数组对象(arguments)转换成数组;遍历类数组; ​ item 表示遍历的元素 fn是每次循环的回调函数 (等同于map方法) ​ dom查询生成的数组是类数组 没有map方法 proto是NodeList 所以类数组只能用Array.from()方法 [图片上传中...(image.png-2fc461-1585363998575-0)] const lis= document.getElementById("li"); ali.map(li =>{ console.log(li)} ); //输出结果为报错 ali.map不是一个函数。因为获取出来的ali是给类数组没有map方法 正确应该如下 Array.from(lis).map() //其他就和正常一样 Array.of() ​ Array.of(n,n)方法 可以将你输入的值 转换为一个有n值的数组; const aa = Array.of(45,5); console.log(aa); //输出结果为 [45,5] 是一个数组 const aa = Array.of(1,2,333333,{}); console.log(aa); //输出结果为 [1,2,333333,{}] 是一个数组 find() ** ​ find( fn( item,index,array) )方法 :用于查找数组中有没有符合条件的的字符串或则是数字 ​ find() 方法返回的是值,当函数return true 时, find 的 返回的是当前的值不是索引,也不是true 或 false。 ​ Caution:find方法找到符合条件后就不会在遍历后面的元素!!!; 意思就是 当回调中有一个返回值为 true时, 就会自动跳出循环,不再执行函数 const arr = [{name:'apples'},{'oranges'},{'bananas'}]; const findApple = arr.find(item=>{item.name==='apples'}) 输出结果为 {name:apples}; 因为利用find的方法 如果找到则返回该元素 ,找不到返回undefined find() 方法为数组中的每个元素都调用一次函数执行: 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。 如果没有符合条件的元素返回 undefined 注意: find() 对于空数组,函数是不会执行的。 注意: find() 并没有改变数组的原始值。 利用 find()检查一个字符串中是否含有你想要的值可以这样做 const arr = ['q','w','e']; const findW = arr.find(item=>{item==='w'}); if(findw!=undefined) { console.log('找到w啦') }else{ console.log('没找到'); } findIndex() ​ 在数组中寻找匹配你输入的值,找到的话则返回数组,找不到就返回-1 ; ​ 用法: 跟find()差不多: find 返回的是对应值, findIndex返回的是索引 some() ​ 用于遍历循环数组,并寻找数组中是否含有你要的数值;有就返回true 后面不进行遍历; const arr = [{age:15},{age:18}]; const findjack = arr.some(item=>{item.age>0}); //输出结果为true 因为age中有一个大于0 ; //一旦有一个符合{}里的表达式 就停止遍历,返回true every() 循环一个数组,只要有一个元素不符合表达式,立马停止循环,返回false; const arr = [{age:15},{age:18}]; const findage = arr.every(item=>{item.age<18}); //輸出結果為false 暂时更新到这里...... 有什么问题需要修正可以直接在下方提,

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):