javascript
JavaScript基础 - 24 (数组方法:every、some、forEach、map、filter、reduce)
1、參數(shù)為回調(diào)函數(shù),function(數(shù)組中的項目,序號,數(shù)組本身){ },至少接收一個項目(item、value)參數(shù)
① every
?????????數(shù)組中所有內(nèi)容都滿足回調(diào)函數(shù)的測試,返回值才為true,否則false,遇假停止,返回false
//value是數(shù)組中的每個元素的值,這個匿名函數(shù)會被數(shù)組循環(huán)調(diào)用var res = nums.every(function(value){//其中內(nèi)容就是對值的判斷條件,例如驗證<50console.log(`當前判斷的值是:${value}`);return value<50;});//如果匿名函數(shù)中的判斷,都是真的,則最終的every的返回值就是真//有任何假的,則返回值就是假console.log(res);//判斷都是偶數(shù)var res1 = nums.every(function(value,index,array){//匿名函數(shù)共有3個參數(shù):值 值的索引 當前數(shù)組。后兩個參數(shù)使用太少了console.log(`${value},${index},[${array}]`);return value%2 == 0;})②some
????????數(shù)組中內(nèi)容存在任意一個滿足回調(diào)函數(shù)的測試的,返回值為true, 否則false,遇真停止,返回
var teachers = [{name:"lily",age:39,married:true},{name:"tom",age:27,married:false},{name:"jack",age:22,married:true},{name:"lucy",age:36,married:false},];//判斷數(shù)組中,是否存在年齡>35的人var result = teachers.some(function(item,index,arr){return item.age>35});console.log(result?"有人年齡>35":"沒有年齡>35的");//判斷是否有已婚的var result = teachers.some(function(item){return item.married})console.log(result?"有已婚":"沒已婚");③forEach
????????遍歷數(shù)組, 每個數(shù)組元素都被 回調(diào)函數(shù)處理
//數(shù)組的forEach方法:快速遍歷數(shù)組var emps = [{name:"丫丫",age:36},{name:"久久",age:19},{name:"明明",age:23},] //為每個年齡+1emps.forEach(function(item){item.age++;})//年齡翻一倍emps.forEach(function(item){item.age*=2})④map
????????創(chuàng)建新數(shù)組,新數(shù)組由回調(diào)函數(shù)的返回值組成
//map:創(chuàng)建一個新的數(shù)組,數(shù)組的值都是回調(diào)函數(shù)的返回值組成的var names = ["lily", "lucy", "john", "tom"];//回調(diào)函數(shù):依然具備三個參數(shù),都是可選的var new_names = names.map(function(item,index,arr){return index + item.toUpperCase()});⑤filter
????????創(chuàng)建新數(shù)組,滿足回調(diào)函數(shù)中的條件的元素, 會加入到新數(shù)組
var emps = [{name:"牛牛",gender:"男",age:20},{name:"丫丫",gender:"女",age:25},{name:"毛毛",gender:"女",age:29},{name:"婷婷",gender:"男",age:32}];//找出所有女性,放在新數(shù)組中var girls = emps.filter(function(item){return item.gender == "女"});//找出年齡<30的var young = emps.filter(function(item){return item.age<30});2、reduce: 合并數(shù)組中的元素的內(nèi)容,形成最終的結(jié)果
????????參數(shù)1:回調(diào)函數(shù):function (合并后的結(jié)果,item,index,arr){ }
? ? ? ?參數(shù)2:合并結(jié)果的初始值
??????? emps.reduce( function(sum,item){return sum + item.salary},0 );
var emps = [{name:"lucy",salary:8000},{name:"mike",salary:5500},{name:"tom",salary:11000},{name:"jerry",salary:7900},];//計算所有工資的總和//forEach寫法:var sum = 0;emps.forEach(function(item){sum += item.salary})//reduce 寫法://參數(shù)1:回調(diào)函數(shù):function (合并后的結(jié)果,item,index,arr){}//參數(shù)2:合并結(jié)果的初始值let result = emps.reduce(function(sum,item){return sum + item.salary},0);總結(jié)
以上是生活随笔為你收集整理的JavaScript基础 - 24 (数组方法:every、some、forEach、map、filter、reduce)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简洁的简历模板_tex版本_面向秋招
- 下一篇: TPS 是一种糟糕的评价标准