繁体   English   中英

javascript使函数内部的变量成为全局变量

[英]javascript make variables inside a function global

我是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对象成为json2对象。

正如其他贡献者告诉您的那样,您必须运行test1()函数。 您可以通过在记录json2变量之前将其添加到代码底部来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

似乎您尚未运行该功能。

在控制台之前运行功能test1。

暂无
暂无

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

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