map函数的使用

map的使用

注意: map() 不会对空数组进行检测。

注意: map() 不会改变原始数组。

语法:

array.map(function(currentValue,index,arr), thisValue)
其中function是必须的。
currentValue:必须。当前元素的值,就是当前角标的数组数据
index:可选。当前元素的索引值
arr: 可选。当前元素属于的数组对象
<div id="demo"></div> 

window.onload= function(){
     var numbers=[11,22,33,44]
     document.getElementById('demo').innerHTML=numbers.map(function(value){return value*2})
}
//显示为 22,44,66,88

高级一些的用法

let r = res.map(item => {
    return {//这里也可以把return省略
        title: item.name,
        sex: item.sex === 1? '男':item.sex === 0?'女':'保密',
        age: item.age,
        avatar: item.img
    }
})

在vue的项目中有空的数组赋值使用

 export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      return {
        firstView: true,
        loading: false,
        users: [],
        errorMsg: ''
      }
    },
    mounted() {
      // 订阅消息(search)
      PubSub.subscribe('search', (message, searchName) => {
        const url = `https://api.github.com/search/users?q=${searchName}`
        // 更新数据(请求中)
        this.firstView = false
        this.loading = true
        this.users = []
        this.errorMsg = ''
        axios.get(url).then(response => {
          // 成功了, 更新数据(成功)
          this.loading = false
          this.users = response.data.items.map(item => ({
            url: item.html,
            avatarUrl: item.avatar_url,
            username: item.login

          }))
        }).catch(error => {
          // 失败了, 更新数据(失败)
          this.errorMsg = '请求失败',
          this.loading = false
        })
      })
    }
  }

其中map的用法是给users为空的数组赋值为对应字段的数组。

 this.users = response.data.items.map(item => ({
            url: item.html,
            avatarUrl: item.avatar_url,
            username: item.login

          }))

  

 

posted on 2020-09-10 17:08  fyccaishao  阅读(328)  评论(0编辑  收藏  举报

导航