# 细说数组常用遍历的方法

## 一、forEach：遍历数组

``````var colors = ["red","blue","green"];
// ES5遍历数组方法
for(var i = 0; i < colors.length; i++){
console.log(colors[i]);//red blue green
}
``````
``````// ES6 forEach
colors.forEach(function(color){
console.log(color);//red blue green
});
``````

``````var numbers = [1,2,3,4,5];
var sum = 0;
numbers.forEach(number=>sum+=number)
console.log(sum)//15
``````

### 二、map：将数组映射成另一个数组

map通过指定函数处理数组的每个元素，并返回处理后新的数组，map 不会改变原始数组。

forEach和map的区别在于，forEach没有返回值。
map需要返回值，如果不给return，默认返回undefined

### 使用场景1

``````var numbers = [1,2,3];
var doubledNumbers = [];
// es5写法
for(var i = 0; i < numbers.length; i++){
doubledNumbers.push(numbers[i] * 2);
}
console.log(doubledNumbers);//[2,4,6]
``````
``````// es6 map方法
var doubled = numbers.map(function(number){
return number * 2;
})
console.log(doubled);//[2,4,6]
``````

### 使用场景2

``````var cars = [
{model:"Buick",price:"CHEAP"},
{model:"BMW",price:"expensive"}
];
var prices = cars.map(function(car){
return car.price;
})
console.log(prices);//["CHEAP", "expensive"]
``````

## 三、filter：从数组中找出所有符合指定条件的元素

filter() 检测数值元素，并返回符合条件所有元素的数组。 filter() 不会改变原始数组。

### 使用场景1

``````var porducts = [
{name:"cucumber",type:"vegetable"},
{name:"banana",type:"fruit"},
{name:"celery",type:"vegetable"},
{name:"orange",type:"fruit"}
];
// es5写法
var filteredProducts = [];
for(var i = 0; i < porducts.length; i++){
if(porducts[i].type === "vegetable"){
filteredProducts.push(porducts[i]);
}
}
console.log(filteredProducts);//[{name: "cucumber", type: "vegetable"},
{name: "celery", type: "vegetable"}]
``````
``````// es6 filter
var filtered2 = porducts.filter(function(product){
return product.type === "vegetable";
})
console.log(filtered2);
``````

### 使用场景2

``````var products = [
{name:"cucumber",type:"vegetable",quantity:0,price:1},
{name:"banana",type:"fruit",quantity:10,price:16},
{name:"celery",type:"vegetable",quantity:30,price:8},
{name:"orange",type:"fruit",quantity:3,price:6}
];
products = products.filter(function(product){
return product.type === "vegetable"
&& product.quantity > 0
&& product.price < 10
})
console.log(products);//[{name:"celery",type:"vegetable",quantity:30,price:8}]
``````

### 使用场景3

``````var post = {id:4,title:"Javascript"};
{postId:4,content:"Angular4"},
{postId:2,content:"Vue.js"},
{postId:3,content:"Node.js"},
{postId:4,content:"React.js"},
];
return comment.postId === post.id;
})
}
``````

## 四、find：返回通过测试（函数内判断）的数组的第一个元素的值

### 使用场景1

`````` var users = [
{name:"Jill"},
{name:"Alex",id:2},
{name:"Bill"},
{name:"Alex"}
];
// es5方法
var user;
for(var i = 0; i < users.length; i++){
if(users[i].name === "Alex"){
user = users[i];
break;//找到后就终止循环
}
}
console.log(user);// {name:"Alex",id:2}
``````
``````// es6 find
user = users.find(function(user){
return user.name === "Alex";
})
console.log(user);// {name:"Alex",id:2}找到后就终止循环
``````

## 使用场景2

``````var posts = [
{id:3,title:"Node.js"},
{id:1,title:"React.js"}
];
var comment = {postId:1,content:"Hello World!"};
function postForComment(posts,comment){
return posts.find(function(post){
return post.id === comment.postId;
})
}
console.log(postForComment(posts,comment));//{id: 1, title: "React.js"}
``````

## 五、every&some

every：数组中是否每个元素都满足指定的条件

some:数组中是否有元素满足指定的条件

### 使用场景1

``````//ES5方法
var computers = [
{name:"Apple",ram:16},
{name:"IBM",ram:4},
{name:"Acer",ram:32}
];
var everyComputersCanRunProgram = true;
var someComputersCanRunProgram = false;
for(var i = 0; i < computers.length; i++){
var computer = computers[i];
if(computer.ram < 16){
everyComputersCanRunProgram = false;
}else{
someComputersCanRunProgram = true;
}
}
console.log(everyComputersCanRunProgram);//false
console.log(someComputersCanRunProgram);//true
``````
``````//ES6 some every
var every = computers.every(function(computer){
return computer.ram > 16;
})
console.log(every);//false
var some = computers.some(function(computer){
return computer.ram > 16;
})
console.log(some);//true
``````

### 使用场景2

``````function Field(value){
this.value = value;
}
Field.prototype.validate = function(){
return this.value.length > 0;
}
//ES5方法
var telephone = new Field("18888888888");
console.log(telephone.validate());//true
``````
``````//ES6 some every
var formIsValid = fields.every(function(field){
return field.validate();
})
console.log(formIsValid);//true
if(formIsValid){
// 注册成功
}else{
// 给用户一个友善的错误提醒
}
``````

## 六、reduce：将数组合成一个值

reduce() 方法接收一个方法作为累加器，数组中的每个值(从左至右) 开始合并，最终为一个值。

### 使用场景1

`````` var numbers = [10,20,30];
var sum = 0;
//es5 方法
for(var i = 0; i < numbers.length; i++){
sum += numbers[i];
}
console.log(sum);
``````
``````// es6 reduce
var sumValue = numbers.reduce(function(sum2,number2){
console.log(sum2);//0 10 30 60
return sum2 + number2;
},0);//sum2初始值为0
console.log(sumValue);
``````

### 使用场景2

`````` var primaryColors = [
{color:"red"},
{color:"yellow"},
{color:"blue"}
];
var colors = primaryColors.reduce(function(previous,primaryColor){
previous.push(primaryColor.color);
return previous;
},[]);
console.log(colors);//["red", "yellow", "blue"]
``````

### 使用场景3

``````function balancedParens(string){
return !string.split("").reduce(function(previous,char){
if(previous < 0) { return previous;}
if(char == "("){ return ++previous;}
if(char == ")"){ return --previous;}
return previous;
},0);
}
console.log(balancedParens("((())))"));
``````

WECHAT：xzsj07