对象和数组
1 let obj = { 2 name:"张三", 3 age:18, 4 like:"音乐,电影" 5 }; 6 let ary = ["chinese",80,"math",90,"english",85]; 7 8 9 //数组转对象: 10 function ao(ary){ 11 let obj1 = {}; 12 for(let i=0;i<ary.length;i++){ 13 let cur = ary[i]; 14 let curn = ary[i+1]; 15 if(i%2===0 && (i+1)%2===1){ 16 obj1[cur] = curn; 17 } 18 } 19 return obj1; 20 }
21 console.log(ao(ary));
如果数组的格式是[{name:'abc',age:18},{name:'efg',age:20},{name:'hij',age:21}]
遍历数组的每一项,拿出每一项的name作为obj1的key,拿出每一项的age作为value,就是将数组每一项改造为key:value的形式存入对象
22
23 //对象转数组: 24 function oa(obj){ 25 let ary1 = []; 26 for(let key in obj){ 27 if(obj.hasOwnProperty(key)){ 28 ary1.push(key);//属性名 29 ary1.push(obj[key]);//属性值 30 } 31 } 32 return ary1; 33 } 34 console.log(oa(obj)); 35 36 //数组克隆: 37 let ary1 = ary.concat(); 38 ary1.pop(); 39 console.log(ary1,ary); 40 41 //对象克隆: 42 let obj1 = {}; 43 for(let key in obj){ 44 if(obj.hasOwnProperty(key)){ 45 obj1[key] = obj[key]; 46 } 47 } 48 obj1.name="李四"; 49 console.log(obj1,obj); 50 51 52 53 console.log(ao(oa(ao(ary))));
深度克隆
1 function deepClone(obj){ 2 let newObj = Array.isArray(obj) ? [] : {}; 3 if(obj && typeof obj === 'object'){ 4 for(let key in obj){ 5 if(obj.hasOwnProperty(key)){ 6 newObj[key] = (obj && typeof obj[key] === 'object') ? deepClone(obj[key]) : obj[key]; 7 } 8 } 9 } 10 return newObj; 11 }
jq的each方法
var obj = { name:'asdf', age:12, sex:0 }; var ary = [12,23,34,45]; //jq遍历数组两种方法结果一样 $.each(ary,function(index,item){ console.log(index,item) }) $(ary).each(function(index,item){ console.log(index,item) }) //jq遍历对象只能用这种方法 $.each(obj,function(key,value){ console.log(key,value) })