数组常用函数

1、filter

clearCompletedTask () {
      // 过滤后的结果为todos数组中每个元素的checked属性为false的元素
      this.todos = this.todos.filter(todo => !todo.checked)
}

2、forEach

selectAll (check) {
      // 遍历todos内的每个元素,为每个元素的checked属性赋值
      this.todos.forEach(todo => { todo.checked = check })
}

3、reduce

checkedTotals () {
      // 统计,初始值为0,todos内的每个元素的checked元素为true时统计结果加1,反之加0
      return this.todos.reduce((preTotal, todo) => preTotal + (todo.checked ? 1 : 0), 0)
}

4、map

mounted () {
    PubSub.subscribe('search', (msg, searchName) => {
      this.firstView = false
      this.loading = true
      this.errorMessage = ''
      this.users = []
      const url = 'https://api.github.com/search/users?q=' + searchName
      axios.get(url).then(response => {
        const result = response.data
        // 返回一个新的数组,新数组中的元素为原始数组元素调用函数处理后的值
        const users = result.items.map(item => {
          return {
            url: item.html_url,
            imgUrl: item.avatar_url,
            name: item.login
          }
        })
        this.users = users
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.errorMessage = '查询失败'
        this.users = []
      })
    })
  }

5、find,只会返回一个对象

// 数组的find方法,当detail.id === this.$route.query.id * 1成立时返回
// this.$route.query.id * 1 是将this.$route.query.id转为Number类型
this.messageDetail = this.messageDetails.find(detail => detail.id === this.$route.query.id * 1)
原文地址:https://www.cnblogs.com/liuyang-520/p/12556039.html