vue学习之路----操作数组的常用方法

2,082 阅读3分钟

对象和数组

vue中经常操作的数据结构就是对象和数组。

数组的变异(下列括号中方法:能改变原数组)

  • 操作数组的一般方法:(pop push unshift shift splice reverse sort) slice indexOf lastIndexof concat

常用的操作数组的方法:forEach filter map some every reduce (find includes)es6

1、for

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) { //编程式,可以看到如何实现
    console.log(arr[i])
}

2、forEach

  • forEach 不支持return,及时添加return也不会阻止循环执行
arr.forEach(function (item) {//声明式,不关心如何实现,item怎样拿到的不知道
    console.log(item);
})

3、for in

如果用for in循环数组会出现以下情况,一般不使用

  • key会变成字符串类型
  • 会将数组的私有属性也遍历出来(下面b为数组的私有属性,使用for in也会遍历出来)
let arr = [1, 2, 3, 4, 5];
arr.b='100'
for(let key in arr){
    console.log(typeof key);
    console.log(key);//0,1,2,3,4,b
}

4、for of

  • 支持return
  • 是值 of 数组 格式(不能遍历对象),不会将私有属性遍历出来
let arr = [1, 2, 3, 4, 5];
arr.b='100'
for (let val of arr){
    console.log(val);
}

使用for of 遍历对象:Object.keys

let obj={name:'zhang',age:12}//Object.keys将对象的key作为新的数组
for (let val of Object.keys(obj)){
    console.log(obj[val]);
}

5、filter

  • 回调函数返回true则将这一项放入新数组中
  • 一般用于删除数组中某些内容
let newAry = [1, 2, 3, 4, 5].filter(function (item) {
    return item > 2 && item < 5
})
console.log(newAry);

6、map

  • 回调函数中返回什么这一项就是什么
  • 更新数组中的内容
let arr1 = [1, 2, 3].map(function (item) {
    return `<li>${item}</li>`
})
console.log(arr1.join(''));

7、includes

let arr3=[1,2,3,4,55]
console.log(arr3.includes(5))//false

这个方法很有局限性,不经常使用

8、find

  • 返回找到的那一项
  • 回调函数中返回true表示找到了,找到后停止循环。找不到返回undefined
  • 找到具体的某一项使用find
let arr3 = [1, 2, 3, 4, 55]
let result = arr3.find(function (item, index) {
    return item.toString().indexOf(5)>-1
})
console.log(result);//55

9、some

  • 返回true
  • 回调函数中找到后停止循环,返回true
  • 找不到返回false
let arr3 = [1, 2, 3, 4, 5]
let result = arr3.some(function (item, index) {
    return item.toString().indexOf(5)>-1
})
console.log(result);//true

10、every

  • 返回false
  • 回调函数找false,找到false后停止,
let arr3 = [1, 2, 3, 4, 5]
let result = arr3.every(function (item, index) {
    return item.toString().indexOf(5)>-1
})
console.log(result);

第一项1就不符合条件,返回false

11、reduce (4个参数)

  • 返回的是叠加后的结果
let sum = [1, 2, 3, 4, 5].reduce(function (prev, next, index, item) {
    return prev + next
})
console.log(sum);

给定第一项的默认值

let sum = [{price: 30, count: 2}, {price: 30, count: 3}, {price: 30, count: 4}].reduce(function (prev, next) {
    return prev + next.price * next.count
}, 0)
console.log(sum);//270

二维数组变为一维数组

let arr=[[1, 2, 3], [4, 5, 6], [7, 8, 9]].reduce(function (prev, next) {
    return prev.concat(next)
})
console.log(arr);

箭头函数

  • 箭头函数不具备this,arguments。自己没有this就找上一级的this

改变this指向的常用方法

  • call apply bind
  • var that=this
  • 箭头函数 如何确定this是谁:看谁调用的,.前面是谁this就是谁
function a(b) {
  return function (c) {
      return b+c
  }  
}

改为箭头函数

let a = b => c => b + c;//高阶函数(两个以上箭头的函数)