前言本文主要介绍常见的数组遍历方法:forEach、map、filter、find、every、some、reduce,它们有一个共同点:不会改变原数组。1.forEach:遍历数组varcolors=["red","blue","green"];//ES5遍历数组方法for(vari=0;isum+=number)console.log(sum)//152.map:映射数组再创建一个数组map,通过指定的函数对数组的每个元素进行处理,并返回处理后的新数组,map不会改变原数组。forEach和map之间的区别在于forEach不返回值。map需要返回一个值,如果不给return,默认返回undefined场景1假设有一个值数组(A),将数组A中的值以double形式放入数组B中varnumbers=[1,2,3];vardoubledNumbers=[];//es5writingfor(vari=0;i0&&product.price<10})console.log(products);//[{name:"celery",type:"vegetable",quantity:30,price:8}]使用场景3:假设有两个数组(A,B),根据A中的id值,过滤掉与B中数组不匹配的数据varpost={id:4,title:"Javascript"};varcomments=[{postId:4,content:"Angular4"},{postId:2,content:"Vue.js"},{postId:3,content:"Node.js"},{postId:4,content:"React.js"},];functioncommentsForPost(post,comments){returncomments.filter(function(comment){returncomment.postId===post.id;})}console.log复制代码(commentsForPost(post,comments));//[{postId:4,content:"Angular4"},{postId:4,content:"React.js"}]4.查找:返回数组中的第一个通过测试(函数内判断)参数为回调函数的元素的值,所有数组成员依次执行回调函数,直到找到第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。使用场景一假设有一个对象数组(A),找到符合条件的对象varusers=[{name:"Jill"},{name:"Alex",id:2},{name:"Bill"},{name:"Alex"}];//es5方法varuser;for(vari=0;i16;})console.log(every);//falsevarsome=computers.some(function(computer){returncomputer.ram>16;})console.log(some);//一句话:some:onetrue是的;every:False为false使用场景2:假设有一个注册页面,判断所有输入内容的长度是否大于0functionField(value){this.value=value;}Field.prototype.validate=function(){returnthis.value.length>0;}//ES5方法varusername=newField("henrywu");vartelephone=newField("18888888888");varpassword=newField("my_password");console.log(username.validate());//trueconsole.log(telephone.validate());//trueconsole.log(password.validate());//true//ES6一些varfields=[username,telephone,password];varformIsValid=fields.every(function(field){returnfield.validate();})console.log(formIsValid);//trueif(formIsValid){//注册成功}else{//给用户友好的错误提示}六、reduce:将数组组合成一个值reduce()方法接受一个方法作为累加器,数组中的值每一个值(从左到右)开始合并,最后成为一个值使用场景一:计算数组varnumbers=[10,20,30]中所有值的和;varsum=0;//es5方法for(vari=0;i