【问题标题】:javascript make variables inside a function globaljavascript使函数内部的变量成为全局变量
【发布时间】:2018-12-10 17:25:24
【问题描述】:

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

【问题讨论】:

  • 你跑过test1()吗?

标签: javascript function execution


【解决方案1】:

正如其他贡献者告诉您的,您必须运行 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

【讨论】:

    【解决方案2】:

    您似乎还没有运行该功能。

    【讨论】:

      【解决方案3】:

      在控制台之前运行函数test1。

      【讨论】:

        猜你喜欢
        • 2015-06-25
        • 2020-04-04
        • 1970-01-01
        • 2023-01-05
        • 2022-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多