js_数组 函数( filter、map、reduce、foreach、findIndex、some )

一:filter() 函数, 过滤

// 基本用法
const nums = [10,20,111,222,444,40,50]			
let newNums2 = nums.filter(item => item < 100)
// 去除数组中的空元素
record = record.filter(function(n){return n})
// 遍历数组,includes是es6中的新方法,在search方法中直接返回新数组
search(keyword){
    return this.urls.filter(item =>{
     if(item.name.includes(keyword)){
      return item
   }
 })
}

二:map() 函数,遍历

// 基础用法
const nums = [10, 20, 111, 222, 444, 40, 50]
let newNums2 = nums.map(item => item *2)

三:reduce() 函数,汇总

const nums = [10, 20, 111, 222, 444, 40, 50]
// reduce 高阶函数
// preVal 遍历的前一个值
// item 遍历的值
// 0 初始化的值,第一次遍历的preVal值就是这个初始化值
let total2 = nums.reduce(function (preVal,item) {
	return preVal + item;
},0)
console.log("reduce:", total2);
// reduce 箭头函数
let total2 = nums.reduce(( preVal , item ) => preVal + item)

四:foreach循环(不能使用return来停止循环)

search(keyword){
var urls = [....] // 处理的元素的集合
var newList = []
urls.forEach(item =>{
   if(item.name.indexOf(keyword) != -1){
      newList.push(item)
   }
})
return newList
}

五:findIndex
返回true后index就是到匹配的元素索引

var urls = [....] // 处理的元素的集合
var index = urls.findIndex(item =>{
      if(item.name == row.name){
       return true;
      }
})
urls.splice(index, 1)

六:some
如果匹配成功就return true跳出some的循环

var urls = [....] // 处理的元素的集合
urls.some((item, i) =>{
  if(item.name == 'str'){
   this.urls.splice(i, 1)
   return true;
  }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值