繁体   English   中英

使用局部或全局变量访问 json 文件的最佳方法是什么?

[英]What is the best way of accessing json file using local or global variable?

I am code for Cordova javascript currently, I am using JSON array object to store examples, questions, answer and more details, approximately the object size is 1MB, and store the objects into a global variable and access it whenever need it like below.

var _quiz=
[{
    v1:1
    ,code:"q1"
    ,type:"x1"
    ,question:"This is the question"
    ,answer:1
    ,options:"Ans1!###Ans2!###Ans3###Ans4"
},
{
    v1:1
    ,type:"x2"
    ,certificate:"bronz"
    ,question:"This is the question"
    ,answer:3
    ,options:"Ans1!###Ans2!###Ans3###Ans4"
}
...
...
];


//Need to call many times
function processQuestion()
{
    _quiz
    ...
    ...
}

但我认为这会在 memory 中占用更多空间,并可能导致应用程序崩溃。 So I think we can store and return the JSON object from the function whenever needs, so it will not take too much memory and objects store as a local variable like the below example. 请建议最好的方法。

function get_object()
{
    var obj=
    [{
        v1:1
        ,code:"q1"
        ,type:"x1"
        ,question:"This is the question"
        ,answer:1
        ,options:"Ans1!###Ans2!###Ans3###Ans4"
    },
    {
        v1:1
        ,type:"x2"
        ,certificate:"bronz"
        ,question:"This is the question"
        ,answer:3
        ,options:"Ans1!###Ans2!###Ans3###Ans4"
    }
    ...
    ...
    ];

    return obj;
}


//Need to call many times
function processQuestion()
{
    var ques=get_object();
    ...
    ...
}

在第二种方法中使用 let 并且您可以做的另一件事是删除 var 声明并直接从 get_object() function 返回 object,因此也有声明,如 return {object}。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM