今天在写代码的是否,碰到如下的数据,我要取值 fvkey,fn,url.
{ "dltype":1, "exem":0, "fl":Object{...}, "hs":0, "ip":"106.39.84.163", "ls":0, "preview":195, "s":"o", "sfl":{ "cnt":0 }, "tm":1498811725, "vl":{ "cnt":1, "vi":[ { "br":121, "ch":0, "cl":{ "fc":0, "keyid":"u0024wqfpsh.2" }, "ct":21600, "drm":0, "dsb":0, "fmd5":"a9fd4f65a9d604a92169be8cdc499caf", "fn":"u0024wqfpsh.mp4", "fs":24395227, "fst":5, "fvkey":"B188B8BAE71DDED428B7781BA026D3343FC3D66A993811ECCC73A48A7CB07415A1DDD320DCA5FD2B581AECE53B07CD536CD553B7E6BC1CF4687B71A13B08ED3CF5198827C699D3895B2FAB93E86EE7A9507E41A26A804DC6", "head":0, "hevc":0, "iflag":0, "level":0, "lnk":"u0024wqfpsh", "logo":1, "mst":8, "pl":Array[1], "share":1, "sp":0, "st":2, "tail":0, "td":"195.2", "ti":"Apink《FIVE》", "type":3585, "ul":{ "ui":[ { "url":"http://106.38.183.14/music.qqvideo.tc.qq.com/", "vt":210, "dtc":0, "dt":2 }, Object{...}, Object{...} ] }, "vh":480, "vid":"u0024wqfpsh", "videotype":22, "vr":0, "vst":2, "vw":848, "wh":1.7666667, "wl":{ "wi":[ ] } } ] } }
于是我毫不犹豫的写下如下的代码,这里的 this.mvinfo就是上面的数据,只不过这段代码是运行在vue程序里面,那么是会被监听的。
没错,代码能够正确运行,也没毛病,只是觉得有点晕。这个时候ES6的结构不是刚好能用上么。
if (this.mvinfo && this.mvinfo.vl && this.mvinfo.vl.vi && this.mvinfo.vl.vi.length > 0) { var vi = this.mvinfo.vl.vi[0] if (vi.fvkey && vi.fvkey && vi.ul.ui && vi.ul.ui.length > 0) { let fvkey = vi.fvkey let fn = vi.fn let bUrl = vi.ul.ui[0].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=121&platform=2&fmt=auto&level=0&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=121&platform=2&fmt=auto&level=0&sdtfrom=v3010&guid=d756e889e0148f3c2eea4f6724d7da9b` } } catch (err) { alert(err) }
是不是完美了,当然不是,错误有这么处理的么。
然后,我先就这样了。