1. 程式人生 > >js 物件型陣列和字串互轉

js 物件型陣列和字串互轉

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
   /*
    *2、陣列轉換成字串    *    ?checked=true|icon='img/icon_a.jpeg'|brand='Apple'....&checked=true|icon='img/icon_b.jpeg'|brand='Oppo'....
*3、把這個字串轉換為物件型陣列*/ var phoneList=[ {checked:true,icon:"img/icon_a.jpeg",brand:"Apple",goods:"Iphone X",num:1, color:"black", price:7988}, {checked:false,icon:"img/icon_b.jpeg",brand:"Oppo",goods:"Oppo R9",num:1, color:"black", price:2500}, {checked:true,icon:"img/icon_c.jpeg"
,brand:"huaWei",goods:"HuaWei",num:1, color:"black", price:2588}, {checked:false,icon:"img/icon_d.jpeg",brand:"Xiaomi",goods:"Note",num:1, color:"black", price:2488}, {checked:true,icon:"img/icon_e.jpeg",brand:"Sanxing",goods:"sanxing",num:1, color:"black", price:8888}, ]; for(var
i=0;i<phoneList.length;i++){ var str="" for(var j in phoneList[i]){ str+=j+"="+phoneList[i][j]+"|" } str=str.slice(0,-1) phoneList[i]=str } var str1="?"+phoneList.join("&") console.log(str1) var str1=str1.slice(1); var arr=str1.split("&"); var list=[]; for(var j=0;j<arr.length;j++){ var objArr=arr[j].split("|") var obj={}; for(var k=0;k<objArr.length;k++){ var objs=objArr[k].split("="); obj[objs[0]]=String(objs[1]).slice(1,-1); } list.push(obj) } console.log(list) </script> </body> </html>