今天在写代码的是否,碰到如下的数据,我要取值 fvkey,fn,url.
{
"dltype":,
"exem":,
"fl":Object{...},
"hs":,
"ip":"106.39.84.163",
"ls":,
"preview":,
"s":"o",
"sfl":{
"cnt":
},
"tm":,
"vl":{
"cnt":,
"vi":[
{
"br":,
"ch":,
"cl":{
"fc":,
"keyid":"u0024wqfpsh.2"
},
"ct":,
"drm":,
"dsb":,
"fmd5":"a9fd4f65a9d604a92169be8cdc499caf",
"fn":"u0024wqfpsh.mp4",
"fs":,
"fst":,
"fvkey":"B188B8BAE71DDED428B7781BA026D3343FC3D66A993811ECCC73A48A7CB07415A1DDD320DCA5FD2B581AECE53B07CD536CD553B7E6BC1CF4687B71A13B08ED3CF5198827C699D3895B2FAB93E86EE7A9507E41A26A804DC6",
"head":,
"hevc":,
"iflag":,
"level":,
"lnk":"u0024wqfpsh",
"logo":,
"mst":,
"pl":Array[],
"share":,
"sp":,
"st":,
"tail":,
"td":"195.2",
"ti":"Apink《FIVE》",
"type":,
"ul":{
"ui":[
{
"url":"http://106.38.183.14/music.qqvideo.tc.qq.com/",
"vt":,
"dtc":,
"dt":
},
Object{...},
Object{...}
]
},
"vh":,
"vid":"u0024wqfpsh",
"videotype":,
"vr":,
"vst":,
"vw":,
"wh":1.7666667,
"wl":{
"wi":[ ]
}
}
]
}
}
于是我毫不犹豫的写下如下的代码,这里的 this.mvinfo就是上面的数据,只不过这段代码是运行在vue程序里面,那么是会被监听的。
没错,代码能够正确运行,也没毛病,只是觉得有点晕。这个时候ES6的结构不是刚好能用上么。
if (this.mvinfo && this.mvinfo.vl && this.mvinfo.vl.vi && this.mvinfo.vl.vi.length > ) {
var vi = this.mvinfo.vl.vi[]
if (vi.fvkey && vi.fvkey && vi.ul.ui && vi.ul.ui.length > ) {
let fvkey = vi.fvkey
let fn = vi.fn
let bUrl = vi.ul.ui[].url
this.src = `${bUrl}${fn}?vkey=${fvkey}&br=121&platform=2&fmt=auto&level=0&sdtfrom=v3010&guid=d756e889e0148f3c2eea4f6724d7da9b`
}
}
重写代码如下, 是不是代码短很多,我可以理解是复杂数据的结构,的确又很精妙, 需要注意的就是
1. 对象数组的结构,取第一个对象应该是 [{p1}],
2. 结构重命名 url: bUrl
let { vl: { vi: [{ fvkey, fn, ul: { ui: [{ url: bUrl }] } }] } } = this.mvinfo || {}
if (fvkey && fn && bUrl) {
this.src = `${bUrl}${fn}?vkey=${fvkey}&br=&platform=&fmt=auto&level=&sdtfrom=v3010&guid=d756e889e0148f3c2eea4f6724d7da9b`
}
这就完了么,当然没有,如果vl就不存在的话,这段代码是会报错的,报错怎么办。try catch 喽,
再调整代码如下,
try {
let { vl: { vi: [{ fvkey, fn, ul: { ui: [{ url: bUrl }] } }] } } = this.mvinfo || {}
if (fvkey && fn && bUrl) {
this.src = `${bUrl}${fn}?vkey=${fvkey}&br=&platform=&fmt=auto&level=&sdtfrom=v3010&guid=d756e889e0148f3c2eea4f6724d7da9b`
}
} catch (err) {
alert(err)
}
是不是完美了,当然不是,错误有这么处理的么。
然后,我先就这样了。