js遍历json对象(推荐)

JavaScript020

js遍历json对象(推荐),第1张

原生js遍历json对象

遍历json对象:

无规律:

有规律:

遍历json对象

有如下 json对象:

var obj ={"name":"冯娟","password":"123456","department":"技术部","sex":"女","old":30}

遍历方法:

数组对象的遍历:

下面我们对照一下js和jquer的遍历方法:

原文网址: https://www.cnblogs.com/qingqingzou-143/p/7079725.html

var jsondata = yourdata

for(var x in jsondata){

document.write(x+"="+jsondata[x])

}

如果是jsonarray就外面套一层for即可

var jsonarray =yourarray

for(var i =0i<jsonarray.lengthi++){

var jsonobj = jsonarray[i]

for(var x in jsonobj){

document.write(x+"="+jsonobj[x])

}

}

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gbk"/>

<script type="text/javascript">

var smsTypeDesc = {"4":"回访短信","3":"邮件短信","aa":"测试短信"}

function EnumaKey(){

for(var key in smsTypeDesc){

alert(key)

}

}

function GetVal(){

var key = prompt("请输入要查询的key","4")

if("undefined"==typeof(smsTypeDesc)) return

if("undefined"==typeof(smsTypeDesc[key])){

alert("输入的key:"+key+", 在json对象中不存在!")

return

}

alert("您输入的key是:"+key + ",该key所对应的值是:"+smsTypeDesc[key])

}

function GetValByKey(){

alert(smsTypeDesc.aa)

}

</script>

</head>

<body>

Json对象:<br/>

<pre>

var smsTypeDesc = {"4":"回访短信","3":"邮件短信","aa":"测试短信"}

</pre>

<input type="button" onclick="EnumaKey()" value="遍历smsTypeDesc所有key"/>

<input type="button" onclick="GetVal()" value="获取smsTypeDesc动态指定key的值"/>

<input type="button" onclick="GetValByKey()" value="获取smsTypeDesc key aa 所对应的值"/>

</body>

</html>