首页 > 解决方案 > javascript使函数内部的变量成为全局变量

问题描述

我是 Java Script 的新手,这就是我所坚持的。我一直在尝试在我的函数中创建一个全局变量,以便我可以在代码的其他部分使用它。到目前为止似乎没有任何工作。下面是我的代码:

var json2="-";

var request = require("request");
var smallpie1 = 
"https://s3.amazonaws.com/vecareclientjson/user1/predictions.json";

var pre = {rejectUnauthorized: false,
       url: smallpie1,
       method: 'GET',
       json: true
};
function test1(){
    request(pre,function (error,response,body){
        json2 = JSON.stringify(body);
        console.log(json2);
    });
};
console.log(json2);

Output:
-
[Done] exited with code=0 in 0.231 seconds

我期待 json 中的内容覆盖 json2 对象。目标是使json2函数内部的对象成为test1()全局对象。

标签: javascriptfunctionexecution

解决方案


正如其他贡献者告诉您的那样,您必须运行该test1()函数。您可以通过在记录json2变量之前将其添加到代码底部来执行此操作,例如:

var json2="-";

var request = require("request");
var smallpie1 = 
"https://s3.amazonaws.com/vecareclientjson/user1/predictions.json";

var pre = {rejectUnauthorized: false,
       url: smallpie1,
       method: 'GET',
       json: true
};
function test1(){
    request(pre,function (error,response,body){
        json2 = JSON.stringify(body);
        console.log(json2);
    });
};

test1(); // Here you call the function, which will modify json2
console.log(json2); // Here you print json2 current value

推荐阅读