亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

細(xì)說數(shù)組常用遍歷的方法

阿羅 / 1208人閱讀

摘要:需要返回值,如果不給,默認(rèn)返回使用場(chǎng)景假定有一個(gè)數(shù)值數(shù)組將數(shù)組中的值以雙倍的形式放到數(shù)組寫法方法使用場(chǎng)景假定有一個(gè)對(duì)象數(shù)組將數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到數(shù)組中三從數(shù)組中找出所有符合指定條件的元素檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。

前言

本文主要介紹數(shù)組常見遍歷方法: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è)賮砜磦€(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通過指定函數(shù)處理數(shù)組的每個(gè)元素,并返回處理后新的數(shù)組,map 不會(huì)改變?cè)紨?shù)組。

forEach和map的區(qū)別在于,forEach沒有返回值。
map需要返回值,如果不給return,默認(rèn)返回undefined

使用場(chǎng)景1
假定有一個(gè)數(shù)值數(shù)組(A),將A數(shù)組中的值以雙倍的形式放到B數(shù)組

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]

使用場(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ù)組中指定類型的對(duì)象放到B數(shù)組中

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);

使用場(chǎng)景2:假定有一個(gè)對(duì)象數(shù)組(A),過濾掉不滿足以下條件的對(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值,過濾掉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:返回通過測(cè)試(函數(shù)內(nèi)判斷)的數(shù)組的第一個(gè)元素的值

它的參數(shù)是一個(gè)回調(diào)函數(shù),所有數(shù)組成員依次執(zhí)行該回調(diào)函數(shù),直到找出第一個(gè)返回值為true的成員,然后返回該成員。如果沒有符合條件的成員,則返回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è)元素都滿足指定的條件

some:數(shù)組中是否有元素滿足指定的條件

使用場(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

一言以蔽之:Some: 一真即真;Every: 一假即假

使用場(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{
  // 給用戶一個(gè)友善的錯(cuò)誤提醒
}
六、reduce:將數(shù)組合成一個(gè)值

reduce() 方法接收一個(gè)方法作為累加器,數(shù)組中的每個(gè)值(從左至右) 開始合并,最終為一個(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ì)稱

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("((())))"));

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/114093.html

相關(guān)文章

  • 細(xì)說數(shù)組常用遍歷方法

    摘要:需要返回值,如果不給,默認(rèn)返回使用場(chǎng)景假定有一個(gè)數(shù)值數(shù)組將數(shù)組中的值以雙倍的形式放到數(shù)組寫法方法使用場(chǎng)景假定有一個(gè)對(duì)象數(shù)組將數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到數(shù)組中三從數(shù)組中找出所有符合指定條件的元素檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。 showImg(https://segmentfault.com/img/remote/1460000016810336?w=1149&h=524);...

    AlphaWatch 評(píng)論0 收藏0
  • 細(xì)說數(shù)組常用遍歷方法

    摘要:需要返回值,如果不給,默認(rèn)返回使用場(chǎng)景假定有一個(gè)數(shù)值數(shù)組將數(shù)組中的值以雙倍的形式放到數(shù)組寫法方法使用場(chǎng)景假定有一個(gè)對(duì)象數(shù)組將數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到數(shù)組中三從數(shù)組中找出所有符合指定條件的元素檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。 showImg(https://segmentfault.com/img/remote/1460000016810336?w=1149&h=524);...

    ?xiaoxiao, 評(píng)論0 收藏0
  • 細(xì)說 Javascript 數(shù)組篇(一) : 數(shù)組遍歷和 length 屬性

    摘要:遍歷為了達(dá)到最佳性能來遍歷一個(gè)數(shù)組,最好的方式就是使用經(jīng)典的循環(huán)。盡管屬性是定義在數(shù)組本身的,但是在循環(huán)的每一次遍歷時(shí)仍然會(huì)有開銷。給屬性賦值一個(gè)更小的數(shù)將會(huì)截?cái)鄶?shù)組,如果賦值一個(gè)更大的數(shù)則不會(huì)截?cái)鄶?shù)組。 盡管數(shù)組在 Javascript 中是對(duì)象,但是不建議使用 for in 循環(huán)來遍歷數(shù)組,實(shí)際上,有很多理由來阻止我們對(duì)數(shù)組使用 for in 循環(huán)。 因?yàn)?for in 循環(huán)將會(huì)枚...

    TigerChain 評(píng)論0 收藏0
  • 「干貨」細(xì)說 Array 常用操作(ES5 和 ES6)

    摘要:今天,會(huì)更具體地將數(shù)組的常用操作進(jìn)行歸納和匯總,以便備不時(shí)之需。在公用庫(kù)中,一般會(huì)這么做的判斷新增的操作和傳入一個(gè)回調(diào)函數(shù),找到數(shù)組中符合當(dāng)前搜索規(guī)則的第一個(gè)元素,返回這個(gè)元素,并且終止搜索。 showImg(https://segmentfault.com/img/bVbpzuS?w=750&h=422); 前言 上一篇文章「前端面試題系列8」數(shù)組去重(10 種濃縮版) 中提到了不少...

    VincentFF 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<