This time I will bring you a summary of js parsing data skills, what are the precautions for js parsing data, the following is a practical case, let's take a look.
Since the separation of front-end and back-end, the data structures provided by some back-end partners have become increasingly confusing. I thought that the separation would reduce their burden. The quality of the interface would be very high, but human laziness is reflected very "perfectly".
Because js is a type language, these errors often occur when using dataTypeError: Cannot read property 'xxx' of undefined TypeError: Cannot read property 'xxx' of null TypeError: xxx.map is not a function
// 第一种做法肯定是这样的 if(a){ return a.name || '你没名字' } // 这种做法处理简单的还能凑合用,但是如果你遇到这样的呢 user.country.area.city.name,难道要这样写 if(user && user.country && user.country.area && user.country.area.city){ return user.country.area.city.name || '你没名字' } // 这是多么痛苦的一件事情 @后端兄弟 // 第二种,感谢es6 let {country={area:{city:{name:'你没名字'}}}} = user; 这个感觉也不是很好的解决方案 // 第三种,利用reduce构建一个解析函数 function getValue(obj,key){ return key.split('.').reduce(function(o,k){ // o,当前对象 // key,数组下一个元素 if((typeof o === 'undefined' || o === null)){ return k.indexOf('[array]') !== -1?[]:o }else{ return k.indexOf('[array]') !== -1?(o[k.replace('[array]','')]||[]):o[k] } },obj) } let user1; let user2 = { } let user3 = { country:{ area:{ city:{ name:'12312' } } } } let user4 = { country:[ { city:{ name:'12312' } } ] } let user5 = { country:{ city:[1,2,3] } } console.log(getValue(user1,'country.area.city.name')) console.log(getValue(user2,'country.area.city.name')) console.log(getValue(user3,'country.area.city.name')) console.log(getValue(user5,'country.city[array]')) console.log(getValue(user5,'country.city[array].1')) console.log(getValue(user5,'country.city[array].10')) console.log(getValue(user5,'country.city[array].1.name')) console.log(getValue(user5,'country.city[array].persion[array]')) // 输出结果 undefined undefined "12312" [1, 2, 3] 2 undefined undefined []
jquery drag file upload loading add progress bar
Detailed explanation of the use of JS prototype and prototype chain
The above is the detailed content of Summary of js data parsing skills. For more information, please follow other related articles on the PHP Chinese website!