萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> JS循環遍歷JSON數據的方法

JS循環遍歷JSON數據的方法

JSON數據如:{"options":"[{/"text/":/"王家灣/",/"value/":/"9/"},{/"text/":/"李家灣/",/"valu
e/":/"10/"},{/"text/":/"邵家灣/",/"value/":/"13/"}]"}

用js可以寫成:

var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}]; 
for(var o in data){ 
alert(o); 
alert(data[o]); 
alert("text:"+data[o].name+" value:"+data[o].age ); 
}

或是

<script type="text/javascript"> 
function text(){ 
var json = {"options":"[{/"text/":/"王家灣/",/"value/":/"9/"},{
/"text/":/"李家灣/",/"value/":/"10/"},{/"text/":/"邵家灣/",/"value/":/"13/"}]"} 
json = eval(json.options) 
for(var i=0; i<json.length; i++) 
{ 
alert(json[i].text+" " + json[i].value) 
} 
} 
</script>

copyright © 萬盛學電腦網 all rights reserved