javascript - 在 Javascript 中为全局数组设置值不起作用
问题描述
我正在尝试根据函数调用的指定选项/值通过函数调用设置全局变量。这是我的代码:
let g_Pl = [];
function prepare() {
let s = 0;
s = 1;
g_Pl[s] = 5;
s = 2;
g_Pl[s] = 8;
s = 3;
g_Pl[s] = 10;
}
function getInfo(s,map,pl) {
switch (map) {
case "test":
pl = g_Pl[s];
break;
}
}
function test() {
let local_Pl;
getInfo(1, "test", local_Pl)
console.log(local_Pl);
}
prepare();
test();
但是控制台输出是“未定义的”,我想知道为什么?local_Pl 应该从 getInfo 中设置一个值,该值必须基于 prepare() 中的参数为“5”:
s = 1;
g_Pl[s] = 5;
为什么它不起作用?
解决方案
您使用pl
andlocal_Pl
作为out
参数又名pass by reference
参数 or ByRef
,但 JavaScript 不支持该功能。您应该返回结果,如下所示:
function getInfo(s, map) {
switch (map) {
case "test":
return g_Pl[s];
}
}
function test() {
let local_Pl = getInfo(1, "test");
console.log(local_Pl);
}
如果您需要返回一些东西并且还有一个 out 参数,那么您可以创建一个对象来包含两者并返回该对象。
function getInfo(s, map) {
var element;
switch (map) {
case "test":
element = g_Pl[s];
break;
}
return { found: !!element, pl: element };
}
function test() {
let result = getInfo(1, "test");
if (result.found) console.log(result.pl);
}
推荐阅读
- jupyter-notebook - Jupyter 笔记本演示 / RISE
- java - 防止与文件的竞争条件
- html - 如何从wordpress中的自定义css中排除特定页面?
- unit-testing - 包含数据库调用的 CakePHP 单元测试组件
- java - JavaMail - 阅读 Outlook 邮件时出现 AuthenticationFailedException
- java - 我们请求长时间运行,UI 在响应准备就绪时超时
- linux - Linux localhost 端口 8080 无响应
- wrapper - 装箱和拆箱平等java
- c - 当我在 C 中更改目录时出现分段错误
- r - 如何阻止R中的引导程序?