javascript - 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()
全局对象。
解决方案
正如其他贡献者告诉您的那样,您必须运行该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
推荐阅读
- javascript - 如何使用keyevents在输入字段中防止负数和超过一定限制的数字,并让用户在可用数字之间循环?
- wordpress - 为多个 wordpress 容器设置 nginx 负载均衡器时出现问题
- java - 无法使用 java 应用程序连接到管理通道
- python-3.x - Python Matplotlib Wordcloud 显示空白
- spring - 麋鹿连接失败
- node.js - 我们可以在 mongoose virtuals 中使用 Query 吗?
- react-native - 华为设备在 react-native-share 中不返回承诺成功或错误
- python - 如何将两个 UUIDv4 字符串组合成一个唯一的 UUIDv4 字符串
- linux - 如何为 docker rootless 安装 uidmap 包
- javascript - 如何在水平滚动上触发交叉点观察者?