本文主要介紹數組常見遍歷方法:forEach、map、filter、find、every、some、reduce,它們有個共同點:不會改變原始數組。愛掏網 - it200.com
如果你想了解塊作用域、promise、class以及ES6環境配置,請猛戳ES6核心特性(一)
如果你想了解解構賦值,箭頭函數以及展開運算符,請猛戳 ES6核心特性(二)
var colors = ["red","blue","green"];
// ES5遍歷數組方法
for(var i = 0; i 復制代碼
// 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 不會改變原始數組。愛掏網 - it200.com
forEach和map的區別在于,forEach沒有返回值。愛掏網 - it200.com map需要返回值,如果不給return,默認返回undefined
使用場景1 假定有一個數值數組(A),將A數組中的值以雙倍的形式放到B數組
var numbers = [1,2,3];
var doubledNumbers = [];
// es5寫法
for(var i = 0; i 復制代碼
// es6 map方法
var doubled = numbers.map(function(number){
return number * 2;
})
console.log(doubled);//[2,4,6]
復制代碼
使用場景2 假定有一個對象數組(A),將A數中對象某個屬性的值存儲到B數組中
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() 檢測數值元素,并返回符合條件所有元素的數組。愛掏網 - it200.com filter() 不會改變原始數組。愛掏網 - it200.com
使用場景1:假定有一個對象數組(A),獲取數組中指定類型的對象放到B數組中
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 if(porducts[i].type === "fruit"){
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,價格小于10
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 "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的成員,然后返回該成員。愛掏網 - it200.com如果沒有符合條件的成員,則返回undefined。愛掏網 - it200.com 使用場景1 假定有一個對象數組(A),找到符合條件的對象
var users = [
{name:"Jill"},
{name:"Alex",id:2},
{name:"Bill"},
{name:"Alex"}
];
// es5方法
var user;
for(var i = 0; 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 if(computer.ram 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
復制代碼
一言以蔽之:Every: 一真即真;Some: 一假即假
使用場景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() 方法接收一個方法作為累加器,數組中的每個值(從左至右) 開始合并,最終為一個值。愛掏網 - it200.com
使用場景1: 計算數組中所有值的總和
var numbers = [10,20,30];
var sum = 0;
//es5 方法
for(var i = 0; i 復制代碼
// 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 return previous;}
if(char == "("){ return ++previous;}
if(char == ")"){ return --previous;}
return previous;
},0);
}
console.log(balancedParens("((())))"));
原文發布時間為:2024年07月01日
原文作者:浪里行舟
本文來源:掘金?如需轉載請聯系原作者