小編給大家分享一下javascript數(shù)組常用的遍歷方法有哪些,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!


前言
本文主要介紹數(shù)組常見(jiàn)遍歷方法:forEach、map、filter、find、every、some、reduce,它們有個(gè)共同點(diǎn):不會(huì)改變?cè)紨?shù)組。
一、forEach:遍歷數(shù)組
var colors = ["red","blue","green"];
// ES5遍歷數(shù)組方法
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
});我們?cè)賮?lái)看個(gè)例子:遍歷數(shù)組中的值,并計(jì)算總和
var numbers = [1,2,3,4,5]; var sum = 0; numbers.forEach(number=>sum+=number) console.log(sum)//15
二、map:將數(shù)組映射成另一個(gè)數(shù)組
map通過(guò)指定函數(shù)處理數(shù)組的每個(gè)元素,并返回處理后新的數(shù)組,map 不會(huì)改變?cè)紨?shù)組。
forEach和map的區(qū)別在于,forEach沒(méi)有返回值。
map需要返回值,如果不給return,默認(rèn)返回undefined
使用場(chǎng)景1
假定有一個(gè)數(shù)值數(shù)組(A),將A數(shù)組中的值以雙倍的形式放到B數(shù)組
var numbers = [1,2,3];
var doubledNumbers = [];
// es5寫(xiě)法
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]使用場(chǎng)景2 假定有一個(gè)對(duì)象數(shù)組(A),將A數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到B數(shù)組中
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:從數(shù)組中找出所有符合指定條件的元素
filter() 檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。 filter() 不會(huì)改變?cè)紨?shù)組。
使用場(chǎng)景1:假定有一個(gè)對(duì)象數(shù)組(A),獲取數(shù)組中指定類(lèi)型的對(duì)象放到B數(shù)組中
var porducts = [
{name:"cucumber",type:"vegetable"},
{name:"banana",type:"fruit"},
{name:"celery",type:"vegetable"},
{name:"orange",type:"fruit"}
];
// es5寫(xiě)法
var filteredProducts = [];
for(var i = 0; i < porducts.length; 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);使用場(chǎng)景2:假定有一個(gè)對(duì)象數(shù)組(A),過(guò)濾掉不滿(mǎn)足以下條件的對(duì)象
條件: 蔬菜 數(shù)量大于0,價(jià)格小于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 < 10
})
console.log(products);//[{name:"celery",type:"vegetable",quantity:30,price:8}]使用場(chǎng)景3:假定有兩個(gè)數(shù)組(A,B),根據(jù)A中id值,過(guò)濾掉B數(shù)組不符合的數(shù)據(jù)
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"}]四、find:返回通過(guò)測(cè)試(函數(shù)內(nèi)判斷)的數(shù)組的第一個(gè)元素的值
它的參數(shù)是一個(gè)回調(diào)函數(shù),所有數(shù)組成員依次執(zhí)行該回調(diào)函數(shù),直到找出第一個(gè)返回值為true的成員,然后返回該成員。如果沒(méi)有符合條件的成員,則返回undefined。
使用場(chǎng)景1
假定有一個(gè)對(duì)象數(shù)組(A),找到符合條件的對(duì)象
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;//找到后就終止循環(huán)
}
}
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}找到后就終止循環(huán)使用場(chǎng)景2:假定有一個(gè)對(duì)象數(shù)組(A),根據(jù)指定對(duì)象的條件找到數(shù)組中符合條件的對(duì)象
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:數(shù)組中是否每個(gè)元素都滿(mǎn)足指定的條件
some:數(shù)組中是否有元素滿(mǎn)足指定的條件
使用場(chǎng)景1:計(jì)算對(duì)象數(shù)組中每個(gè)電腦操作系統(tǒng)是否可用,大于16位操作系統(tǒng)表示可用,否則不可用
//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一言以蔽之:Every: 一真即真;Some: 一假即假
使用場(chǎng)景2:假定有一個(gè)注冊(cè)頁(yè)面,判斷所有input內(nèi)容的長(zhǎng)度是否大于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){
// 注冊(cè)成功
}else{
// 給用戶(hù)一個(gè)友善的錯(cuò)誤提醒
}六、reduce:將數(shù)組合成一個(gè)值
reduce() 方法接收一個(gè)方法作為累加器,數(shù)組中的每個(gè)值(從左至右) 開(kāi)始合并,最終為一個(gè)值。
使用場(chǎng)景1: 計(jì)算數(shù)組中所有值的總和
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);使用場(chǎng)景2:
將數(shù)組中對(duì)象的某個(gè)屬性抽離到另外一個(gè)數(shù)組中
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"]使用場(chǎng)景3:判斷字符串中括號(hào)是否對(duì)稱(chēng)
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("((())))"));看完了這篇文章,相信你對(duì)javascript數(shù)組常用的遍歷方法有哪些有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線(xiàn),公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。
文章標(biāo)題:javascript數(shù)組常用的遍歷方法有哪些-創(chuàng)新互聯(lián)
新聞來(lái)源:http://chinadenli.net/article38/hcosp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、企業(yè)網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè)、ChatGPT、云服務(wù)器、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容