JS中判斷JSON數據是否存在某字段的方法 JavaScript中判斷json中是否有某個字段


方式一 !("key" in obj) 
方式二 obj.hasOwnProperty("key")  //obj為json對象。

實例:

        var jsonworld_pose = JSON.parse(data[0].world_pose);
        var jsonorientation = jsonworld_pose.orientation; //次處可能為undefined
        var jsonposition = jsonworld_pose.position;//次處可能為undefined

        if (jsonworld_pose.hasOwnProperty("orientation")) {//使用時先進行判斷
            $("#orientation-w").html(jsonorientation.w);
            $("#orientation-x").html(jsonorientation.x);
            $("#orientation-y").html(jsonorientation.y);
            $("#orientation-z").html(jsonorientation.z);
        }

        if (jsonworld_pose.hasOwnProperty("position")) {
            $("#position-x").html(jsonposition.x);
            $("#position-y").html(jsonposition.y);
            $("#position-z").html(jsonposition.z);
        }

 


免責聲明!

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



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