1.JSON转换
//var str = ' {"name": "heihei","age": "12"}'; //var obj = {"name": "heihei","age": "12"}; //JSON.parse(str).log//将JSON格式字符串,转化成JSON格式对象 //JSON.stringify(obj).log//将JSON格式对象,转化成JSON格式字符串
2.JS 异常捕捉
try { console.log(num) }catch (e) { // 形参必须写,形参名字 自己定义,一般起名e console.log('出错了'); console.log(e.message);// e.message 收集当前代码报错的原因 throw new Error('你长得太丑了,不准打开此页面') }finally { console.log('不管是否报错都要执行这里'); // 一般不使用
3.类数组 转换 成数组
function toAry (n1, n2, n3, n4, n5) { var ary = [].slice.call(arguments); var aryTwo = Array.prototype.slice.call(arguments); console.log(ary,aryTwo); } // IE 6-8不兼容 toAry(1,2,3,4,5); // 兼容写法 function toA (obj) { var ary = []; for (var i=0; i<ary.length;i++) { ary[ary.length] = obj[i] } return ary; } toA()
4.utils
function listToArray (obj) { var ary = []; try { ary = Array.prototype.slice.call(obj) }catch (e) { for (var i=0; i<obj.length;i++) { ary[ary.length] = obj[i] } } return ary; } function JSONParse (str) { var val; try { val = JSONParse(str) }catch (e){ val = eval("("+str+")"); } return val; return JSON in window ? JSONParse(str):eval("("+str+")"); }
5.Main
var main = { JSONTrans: function (obj) { if (window.JSON) { return JSON.parse(obj); }else { return eval("("+ obj +")"); } }, tryJson: function (obj) { var res = null; try { res = JSON.parse(obj); } catch (e) { // 储存的是报错信息,必须要写 res = eval("(" + obj + ")"); } return res; }, toAr: function (n) { // var newAry = Array.apply(null,n);//通过构造函数以函数身份运行,来创建数组.这个方法在IE8以下不兼容传类数组 var newAry2 = [].slice.call(n);// 调用数组中的slice克隆数组的方法,改变方法中this的指向 return newAry2; } };
6.中文排序
var aryNew = [ {name:'小满',age:3}, // AXUAN {name:'张',age:12},// DAWEISUOYAO {name:'帅哥',age:63},// SHUAIGE {name:'猥琐哥',age:103},// WEISUOGE {name:'盛尧',age:2004},// SHENGYAO {name:'安迪',age:15}// LIYUAN ]; var theAry = aryNew.sort(function (a, b) { return a.name.localeCompare(b.name); }); console.log(theAry);