简体   繁体   English

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

[英]javascript make variables inside a function global

I'm new to Java Script and here's what I'm stuck with. 我是Java脚本的新手,这就是我要坚持的东西。 I've been trying to make a variable inside my function global so that I could use it in the other parts of the code. 我一直在尝试使函数内部的变量成为全局变量,以便可以在代码的其他部分中使用它。 Nothing seems to be working so far. 到目前为止,似乎没有任何工作。 Below is my code: 下面是我的代码:

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

I was expecting the content in the json to overwrite the json2 object. 我期望json中的内容覆盖json2对象。 The goal is to make the json2 object inside the function test1() global. 目标是使函数test1()json2对象成为json2对象。

As other contributers are telling you, you must run the test1() function. 正如其他贡献者告诉您的那样,您必须运行test1()函数。 You can do so by adding it to the bottom of your code, before logging the json2 variable, such as: 您可以通过在记录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