Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript使函数中的变量成为全局变量_Javascript_Function_Execution - Fatal编程技术网

javascript使函数中的变量成为全局变量

javascript使函数中的变量成为全局变量,javascript,function,execution,Javascript,Function,Execution,我不熟悉Java脚本,下面是我一直坚持的。 我一直在尝试在我的函数中创建一个全局变量,以便在代码的其他部分使用它。到目前为止,一切似乎都不起作用。下面是我的代码: var json2="-"; var request = require("request"); var smallpie1 = "https://s3.amazonaws.com/vecareclientjson/user1/predictions.json"; var pre = {rejectUnauthorized: f

我不熟悉Java脚本,下面是我一直坚持的。 我一直在尝试在我的函数中创建一个全局变量,以便在代码的其他部分使用它。到目前为止,一切似乎都不起作用。下面是我的代码:

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对象。
目标是使函数
test1()
中的
json2
对象成为全局对象。

您似乎还没有运行该函数。

正如其他参与者告诉您的那样,您必须运行
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

在console之前运行函数test1。

您是否运行过
test1()