Js 怎么遍歷json對象所有key及根據動態key獲取值


js訪問json參照一下代碼

<html>  
<head>  
    <meta http-equiv="Content-Type" content="text/html; charset=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>  

通過上面的代碼可以看出  js訪問json的值主要是通過   “鍵”“值”的方式來訪問的,

摘自http://blog.csdn.net/love__coder/article/details/7532616 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM