ES6 数组的一些常用API

注意箭头函数写法:

let list = [1,2]
let list1 = list.filter(el=>{ el != 1 }) // 没有加return ,无值返回
console.log(list1) // []  

let list = [1,2]
let list1 = list.filter(el=>{ return el != 1 }) // 加{} ,需加return
console.log(list1) // [2]  

let list = [1,2]
let list1 = list.filter(el=>el != 1) // 无{}时 ,也无需加return
console.log(list1) // [2] 

every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。

// const isBelowThreshold = (currentValue) => currentValue < 40;
// const array1 = [1, 30, 39, 29, 10, 13];
// console.log(array1.every(isBelowThreshold)); // true 数组中的值都小于 40

 filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的部分元素。 

// 案列1
function isBigEnough(element) {
      return element >= 10;
    }
    var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
    console.log(filtered) //[12, 130, 44]

    // var filtered = [12, 5, 8, 130, 44].filter(i=> {i > 10}); // 写法有问题
    // console.log(filtered) // []
    var filtered = [12, 5, 8, 130, 44].filter(i=> {return i > 10});
    console.log(filtered) //[12, 130, 44]
    var filtered = [12, 5, 8, 130, 44].filter(i=> i > 10);
    console.log(filtered) //[12, 130, 44]

    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    const result = words.filter(word => word.length > 6);
    console.log(result); // ['exuberant', 'destruction', 'present']

// 案列2
let list = [1,2]
let list1 = list.filter(el=>{
	return el != 1  // 从list数组中过滤掉1的值
})
console.log(list1);  // [2]

 some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。

// const array = [1, 2, 3, 4, 5];
// const even = (element) => element > 2;
// console.log(array.some(even)); //true 有一个元素值大于2

  reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => {
  accumulator + currentValue
  console.log(`accumulator: ${accumulator}`);
  console.log(`currentValue: ${currentValue}`);
};

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // 10
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5)); // 15 10 + 5 

 reduce购物车案例:

// 购物车的案例
let arr = [
  {
    num: 1,
  },
  { num: 2 },
  { num: 3 },
];

let res = arr.reduce((pre, next, index, list) => {
  console.log(pre); // 不给默认值0输出为{num: 1},pre为上一次计算出来的值 0 1 3
  // console.log(next); // {num: 2} {num: 3} 循环的item除去了0这个item,是由于pre为0的item
  // console.log(index); // 1 2 索引同上
  // console.log(list); // [{…}, {…}, {…}], [{…}, {…}, {…}]
  return pre + next.num;
}, 0); // 给pre一个默认值为0
console.log(res);

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

 map() 方法创建一个新数组或者是对数据加工

let list = [2,3]
    let newList =  list.map(item=>{
      return item * 2
    })
console.log(newList) // [4, 6]

//需求对数组加工,每个对象加个id子段
let list = [{a:1},{b:2}]
let data = list.map(item=>{item.id=9; return item})
console.log(data ) // [{a: 1, id: 9}, {b: 2, id: 9}]

find() 方法返回数组中满足提供的测试函数的第一个元素的值

let a = [1,23,4]
let b = a.find(i=>i>2)
console.log(b) // 23

findIndex方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。

findIndex与indexOf相比 findIndex能对数组中的对象处理

let list = ['a','b','c']
let index = list.findIndex(item=>{
    return item === 'b'
           
})
console.log(index); // 1
let b = list.indexOf('b')
console.log(b); // 1


let list = [{'layer': 'a','id':1},{'layer': 'b','id':2}]
let index = list.findIndex(item=>{
    return item.id === 2           
})
console.log(index); //1
        
let b = list.indexOf('b') // 则无法处理

splice()方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组

 array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

参数 start 索引开始值;deleteCount(可选) 删除或替换的个数,item,item2...(可选)要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素。

let list = ['one', 'two', 'three']
let list1 = list.splice(1,1) // 删除数组中索引为1的值,并且不在此添加元素
console.log(list1); // 返回被删除的值 ['two']
console.log(list); // ['one', 'three']

let list = ['one', 'two', 'three']
let list1 = list.splice(0,1,'four')
console.log(list1); // 返回被删除的值 ['one']
console.log(list); // ['four', 'two', 'three']

let list = ['one', 'two', 'three']
let list1 = list.splice(0, 0,'four')
console.log(list1); // 返回被删除的值 [] ,为空没有值删除
console.log(list); //  ['four', 'one', 'two', 'three']

let list = ['one', 'two', 'three']
let list1 = list.splice(0, 2)
console.log(list1); // 返回被删除的值['three'] ,为空没有值删除
console.log(list); //  ['one', 'two']

slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

[1,2,3,4,5].slice(0,3)  //从索引0开始至 索引3之前截止 [1, 2, 3]
[1,2,3,4,5].slice(3,[1,2,3,4,5].length) // [4,5] 截取到列表最后

综合案列:

0.forEach 和filter 和map 的区别

let list = [
      { id: 1, name: "工程车作业" },
      { id: 5, name: "生物质燃烧" },
      { id: 7, name: "扬尘" }
    ]

    let c = []
    list.forEach((a) => {
      if (![5].includes(a.id)) {
        c.push(a.id) // 处理返回新的数组
      }
    })
    console.log(c) // [1,7]

    let d = list.filter((a) => {
      if (![5].includes(a.id)) {
        // return a
        // return a.id
        return 1 // reurn什么返回的都是item,filter是过滤不符合条件的item
      }
    })
    console.log(d) //[ { id: 1, name: '工程车作业' }, { id: 7, name: '扬尘' } ]

    let newList = list.map((a) => { //map对数组加工,对每个item 加工
      if (![5].includes(a.id)) {
        console.log(a)
        return a.id
      }
    })
    console.log('new List', newList) // [1, undefined, 7]
    console.log(newList.length) // 3

1.根据id去重

let students=[
    {
        id:5,
        name:'守候',
        sex:'男',
        age:'',
    },
    {
        id:2,
        name:'浪迹天涯',
        sex:'男',
        age:''
    },
    {
        id:5,
        name:'守候',
        sex:'',
        age:''
    },
    {
        id:3,
        name:'鸿雁',
        sex:'',
        age:'20'
    }
];

 function removeRepeat(arr) { // 根据id 去重
    let _arr = []
    let arrid = [] // 存放id
    arr.forEach(item=>{ 
      let isExist = arrid.find(j=>j === item.id)  // 查找是否有当前id存在
      !isExist ? _arr.push(item) : ''
      arrid.push(item.id)
    })
    return _arr
  }

let newStudents = removeRepeat(students)
console.log(newStudents)

2.根据数组索引值删除元素

let list = [{'layer': 'a','id':1},{'layer': 'b','id':2}]
et index = list.findIndex(item=>{
    return item.id === 2           
})
console.log(index); //1
list.splice(index,1) // 从索引1的位置删除一个元素
console.log(list); // [{'layer': 'a','id':1}]

3.模糊匹配数组 filter

//1 
let a = ["秦家屯镇污水处理厂", "东家", '东1']
let list = a.filter(item => {
  return item.indexOf("东") > -1
})

console.log(list) //[ '东家', '东1' ]

//2
this.timer = null;
this.surfaces = [{name:123},{name:34}]
if(this.timer) {
		clearTimeout(this.timer)
				}
				this.timer = setTimeout(()=>{
					this.timer = null
					this.getSearchList(val)
				},1000)


getSearchList(val) {
				this.searchs = []
				this.surfaces.forEach(item => {
				  if(item.name.indexOf(val) > -1) {
						this.searchs.push(item)
					}
				})
				console.log(this.searchs)
			}

4.数组的item中增加一条数据

let list = [
  { id: 48, sname: "两河口" },
  { id: 49, sname: "平滩" }
]

// {}中只有一行代码时,如省略写法必须return 和 {} 一起省略否则返回的结果不正确
let o = list.filter(item =>
  item.newName = item.sname + '测试'
)
console.log(o) //[ { id: 48, sname: '两河口', newName: '两河口测试' },{ id: 49, sname: '平滩', newName: '平滩测试' }]

let remark = null
let o2 = list.filter(item => {
  let rem = remark === null ? '是null' : '不是null'
  item.newName = item.sname + rem
  return item  // return item 类似与push(item)
}
)
console.log(o2) // [{ id: 48, sname: '两河口', newName: '两河口null' },{ id: 49, sname: '平滩', newName: '平滩null' }]

5.filter和find的区别

let obj = [{name:'cookie',id:1}]
let c = obj.filter(v=>v.id===1)
console.log(c)  // [{ name: "cookie", id: 1 }] 得到的是数组
console.log(c[0].id) // 1


let obj = [{name:'cookie',id:1}]
let c = obj.find(v=>v.id===1)
console.log(c)  // { name: "cookie", id: 1 } 得到的是对象
console.log(c[0].id) // 1

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值