chararray遍历_数组常⽤的遍历⽅法——总结
看图了解数组常⽤的⽅法
前⾔
本⽂主要介绍数组常见遍历⽅法:forEach、map、filter、find、every、some、reduce,它们有个共同点:不会改变原始数组。
⼀、forEach:遍历数组
1 var colors = ["red","blue","green"];
2 //ES5遍历数组⽅法
3 for(var i = 0; i < colors.length; i++){
4 console.log(colors[i]);//red blue green
5 }
1 //ES6 forEach
2 colors.forEach(function(color){
3 console.log(color);//red blue green
4 });
我们再来看个例⼦:遍历数组中的值,并计算总和
1 var numbers = [1,2,3,4,5];
2 var sum = 0;
3 numbers.forEach(number=>sum+=number)
4 console.log(sum)//15
⼆、map:将数组映射成另⼀个数组
map通过指定函数处理数组的每个元素,并返回处理后新的数组,map 不会改变原始数组。
forEach和map的区别在于,forEach没有返回值。
map需要返回值,如果不给return,默认返回undefined
使⽤场景1
假定有⼀个数值数组(A),将A数组中的值以双倍的形式放到B数组
1 var numbers = [1,2,3];
2 var doubledNumbers =[];
3 //es5写法
4 for(var i = 0; i < numbers.length; i++){
5 doubledNumbers.push(numbers[i] * 2);
6 }7
console.log(doubledNumbers);//[2,4,6]
1 //es6 map⽅法
2 var doubled = numbers.map(function(number){
3 return number * 2;
4 })
5 console.log(doubled);//[2,4,6]
使⽤场景2 假定有⼀个对象数组(A),将A数中对象某个属性的值存储到B数组中
1 var cars =[
2 {model:"Buick",price:"CHEAP"},
3 {model:"BMW",price:"expensive"}
4 ];
5 var prices = cars.map(function(car){
6 returncar.price;
7 })
8 console.log(prices);//["CHEAP", "expensive"]
三、filter:从数组中出所有符合指定条件的元素
filter() 检测数值元素,并返回符合条件所有元素的数组。 filter() 不会改变原始数组。
使⽤场景1:假定有⼀个对象数组(A),获取数组中指定类型的对象放到B数组中
1 var porducts =[
2 {name:"cucumber",type:"vegetable"},
3 {name:"banana",type:"fruit"},
4 {name:"celery",type:"vegetable"},
5 {name:"orange",type:"fruit"}
6 ];
7 //es5写法
8 var filteredProducts =[];9 for(var i = 0; i < porducts.length; i++){10 if(porducts[i].type === "vegetable"){11 filteredProducts.push(porducts[i]);12 }13 }14 console.log(filteredProducts);//[{name: "cucumber", type: "vegetable"},
15 {name: "celery", type: "vegetable"}]
1 //es6 filter
2 var filtered2 = porducts.filter(function(product){
3 pe === "vegetable";
4 })
5 console.log(filtered2);
使⽤场景2:假定有⼀个对象数组(A),过滤掉不满⾜以下条件的对象
条件: 蔬菜 数量⼤于0,价格⼩于10
1 var products =[
2 {name:"cucumber",type:"vegetable",quantity:0,price:1},3
{name:"banana",type:"fruit",quantity:10,price:16},4 {name:"celery",type:"vegetable",quantity:30,price:8},5 {name:"orange",type:"fruit",quantity:3,price:6}6 ];7 products = products.filter(function(product){8 pe === "vegetable"
9 && product.quantity > 0
10 && product.price < 10
11 })12 console.log(products);//[{name:"celery",type:"vegetable",quantity:30,price:8}]
使⽤场景3:假定有两个数组(A,B),根据A中id值,过滤掉B数组不符合的数据
1 var post = {id:4,title:"Javascript"};
2 var comments =[
3 {postId:4,content:"Angular4"},
4 {postId:2,content:"Vue.js"},
5 {postId:3,content:"Node.js"},
6 {postId:4,content:"React.js"},
7 ];
8 functioncommentsForPost(post,comments){
9 return comments.filter(function(comment){10 return comment.postId ===post.id;11 })12 }13
console.log(commentsForPost(post,comments));//[{postId:4,content:"Angular4"},{postId:4,content:"React.js"}]
四、find:返回通过测试(函数内判断)的数组的第⼀个元素的值
它的参数是⼀个回调函数,所有数组成员依次执⾏该回调函数,直到出第⼀个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。
使⽤场景1
假定有⼀个对象数组(A),到符合条件的对象
1 var users =[
2 {name:"Jill"},
3 {name:"Alex",id:2},
4 {name:"Bill"},
5 {name:"Alex"}
6 ];
7 //es5⽅法
8 varuser;9 for(var i = 0; i < users.length; i++){10 if(users[i].name === "Alex"){11 user =users[i];12 break;//到后就终⽌循环
13 }14 }15 console.log(user);//{name:"Alex",id:2}
1 //es6 find
2 user = users.find(function(user){
3 return user.name === "Alex";
4 })
5 console.log(user);//{name:"Alex",id:2}到后就终⽌循环
使⽤场景2:假定有⼀个对象数组(A),根据指定对象的条件到数组中符合条件的对象
1 var posts =[
2 {id:3,title:"Node.js"},
3 {id:1,title:"React.js"}
4 ];
5 var comment = {postId:1,content:"Hello World!"};
6 functionpostForComment(posts,comment){
7 return posts.find(function(post){
8 return post.id ===comment.postId;
9 })10
}11 console.log(postForComment(posts,comment));//{id: 1, title: "React.js"}
五、every&some
every:数组中是否每个元素都满⾜指定的条件
some:数组中是否有元素满⾜指定的条件
使⽤场景1:计算对象数组中每个电脑操作系统是否可⽤,⼤于16位操作系统表⽰可⽤,否则不可⽤
1 //ES5⽅法
2 var computers =[
3 {name:"Apple",ram:16},
filter过滤对象数组
4 {name:"IBM",ram:4},
5 {name:"Acer",ram:32}
6 ];
7 var everyComputersCanRunProgram = true;
8 var someComputersCanRunProgram = false;
9 for(var i = 0; i < computers.length; i++){10 var computer =computers[i];11 if(computer.ram < 16){12 everyComputersCanRunProgram = false;13 }else{14 someComputersCanRunProgram = true;15 }16 }17 console.log(everyComputersCanRunProgram);//false
18 console.log(someComputersCanRunProgram);//true
1 //ES6 some every
2 var every = computers.every(function(computer){
3 return computer.ram > 16;
4 })
5 console.log(every);//false
6 var some = computers.some(function(computer){
7 return computer.ram > 16;
8 })
9 console.log(some);//true
⼀⾔以蔽之:Some: ⼀真即真;Every: ⼀假即假
使⽤场景2:假定有⼀个注册页⾯,判断所有input内容的长度是否⼤于0
1 functionField(value){
2 this.value =value;
3 }
4 Field.prototype.validate = function(){
5 return this.value.length > 0;
6 }
7 //ES5⽅法
8 var username = new Field("henrywu");9 var telephone = new Field("188********");10 var password = new
Field("my_password");11 console.log(username.validate());//true
12 console.log(telephone.validate());//true
13 console.log(password.validate());//true
14 //ES6 some every
15 var fields =[username,telephone,password];16 var formIsValid = fields.every(function(field){17 returnfield.validate();18 })19 console.log(formIsValid);//true
20 if(formIsValid){21 //注册成功
22 }else{23 //给⽤户⼀个友善的错误提醒
24 }
六、reduce:将数组合成⼀个值
reduce() ⽅法接收⼀个⽅法作为累加器,数组中的每个值(从左⾄右) 开始合并,最终为⼀个值。
使⽤场景1: 计算数组中所有值的总和
1 var numbers = [10,20,30];
2 var sum = 0;
3 //es5 ⽅法
4 for(var i = 0; i < numbers.length; i++){
5 sum +=numbers[i];
6 }
7 console.log(sum);
1 //es6 reduce
2 var sumValue = duce(function(sum2,number2){
3 console.log(sum2);//0 10 30 60
4 return sum2 +number2;
5 },0);//sum2初始值为0
6 console.log(sumValue);
使⽤场景2:
将数组中对象的某个属性抽离到另外⼀个数组中
1 var primaryColors =[
2 {color:"red"},
3 {color:"yellow"},
4 {color:"blue"}
5 ];
6 var colors =
使⽤场景3:判断字符串中括号是否对称
1 functionbalancedParens(string){
2 return !string.split("").reduce(function(previous,char){
3 if(previous < 0) { returnprevious;}
4 if(char == "("){ return ++previous;}
5 if(char == ")"){ return --previous;}
6 returnprevious;
7 },0);
8 }
9 console.log(balancedParens("((())))"));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。