从QQ音乐返回的数据不是我们想要的,所以要对res.data.list进行在加工,以便于dom操作
_getSingerList () {
getSingerList().then((res) => {
if (res.code === ERR_OK) {
this.singer = res.data // 得到的 数据不是object类型 所以要转变为object
this.list = this._nomalSingerList(this.singer.list)
// console.log(this.list)
}
})
},
_nomalSingerList(list){
//定义一个对象,对象包含hot和key多个对象
let map = {
hot: {
title: '热门',
items: []
}
}
//遍历list, 将list的数据分门别类的分开
list.forEach((item, index) = >{
if (index < 10) { // 取index前十个为热门歌手
map.hot.item.push(new Singer({ // 定义的Singer Class
name: item.Fsinger_name, // 这是返回的数据
id: item.Fsinger_mid
})
}
// 定义map的其他名字为首字母的对象
const key = item.Findex // 返回的数据,是歌手名称首字母
if (!map.[key]){ // 如果没有该首字母的对象,则创建新的对象
map[key] = {
title: key,
items: []
}
}
map.[key].push(new Singer({ // 将所有的歌手都分到专属对象中
name: item.Fsinger_name,
id: item.Fsinger_mid
}))
})
// 为map对象中的元素进行排序
let hotSinger = [] // 建立两个数组放数据
let retSinger = []
// 遍历map对象
for(let key in map){
let val = map[key]
if (val.title.match(/[a-zA-Z]/) { // 若title是a-z,就push到retSinger数组中,其他(即title为‘热门’)push到hotSinger
retSinger.push(val)
} else {
hotSinger.push(val)
}
}
// 对ret数组进行排序
retSinger.sort(a, b, () => {
return a.title.charCodeAt(0) - b.title.charCodeAt(0) // 升序排列
}
//整体函数返回一个大数组
return hotSinger.concat(retSinger) // 将两个小数组合并 并返回
}
最终得到一个大数组,便于dom操作
charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。
array.sort()方法默认是升序排序,如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值(a, b),然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:
若 a 小于 b,升序,在排序后的数组中 a 应该出现在 b 之前,则返回-1 。简写 return a-b
若 a 等于 b,则返回 0。
若 a 大于 b,则返回1 。