本文主要介紹數組常見遍歷方法:forEach、map、filter、find、every、some、reduce,它們有個共同點:不會改變原始數組。es6
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 不會改變原始數組。函數
forEach和map的區別在於,forEach沒有返回值。
map須要返回值,若是不給return,默認返回undefinedpost
使用場景1
假定有一個數值數組(A),將A數組中的值以雙倍的形式放到B數組測試
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 假定有一個對象數組(A),將A數中對象某個屬性的值存儲到B數組中ui
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() 不會改變原始數組。this
使用場景1:假定有一個對象數組(A),獲取數組中指定類型的對象放到B數組中es5
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:假定有一個對象數組(A),過濾掉不知足如下條件的對象
條件: 蔬菜 數量大於0,價格小於10spa
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:假定有兩個數組(A,B),根據A中id值,過濾掉B數組不符合的數據操作系統
var post = {id:4,title:"Javascript"}; var comments = [ {postId:4,content:"Angular4"}, {postId:2,content:"Vue.js"}, {postId:3,content:"Node.js"}, {postId:4,content:"React.js"}, ]; function commentsForPost(post,comments){ return comments.filter(function(comment){ return comment.postId === post.id; }) } console.log(commentsForPost(post,comments));//[{postId:4,content:"Angular4"},{postId:4,content:"React.js"}]
它的參數是一個回調函數,全部數組成員依次執行該回調函數,直到找出第一個返回值爲true的成員,而後返回該成員。若是沒有符合條件的成員,則返回undefined。
使用場景1
假定有一個對象數組(A),找到符合條件的對象
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:假定有一個對象數組(A),根據指定對象的條件找到數組中符合條件的對象
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:數組中是否有元素知足指定的條件
使用場景1:計算對象數組中每一個電腦操做系統是否可用,大於16位操做系統表示可用,不然不可用
//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
一言以蔽之:Some: 一真即真;Every: 一假即假
使用場景2:假定有一個註冊頁面,判斷全部input內容的長度是否大於0
function Field(value){ this.value = value; } Field.prototype.validate = function(){ return this.value.length > 0; } //ES5方法 var username = new Field("henrywu"); var telephone = new Field("18888888888"); var password = new Field("my_password"); console.log(username.validate());//true console.log(telephone.validate());//true console.log(password.validate());//true //ES6 some every var fields = [username,telephone,password]; var formIsValid = fields.every(function(field){ return field.validate(); }) console.log(formIsValid);//true if(formIsValid){ // 註冊成功 }else{ // 給用戶一個友善的錯誤提醒 }
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("((())))"));