【发布时间】:2019-12-10 00:47:55
【问题描述】:
我正在尝试创建一个全局变量以在其他函数中使用。我正在创建条件语句,以便我可以在多个函数中使用这些变量,而无需编写冗余代码。
let x = "";
if (filters.group == "day") {
x = new Date(elem.date);
} else if (filters.grou == "month") {
x = new Date(elem.year, elem.month)
}
使用的函数:
$.getJSON(jsonOne, result => {
result.forEach(elem => {
series1.data.push({
x: +xaxis,
y: elem.starts
});
series2.data.push({
x: +xaxis
y: elem.completes
});
});
});
$.getJSON(jsonTwo, result => {
result.forEach(elem => {
series3.data.push({
x: +xaxis,
y: elem.rev
});
series4.data.push({
x: +xaxis,
y: elem.val
});
});
}),
错误:
Uncaught ReferenceError: elem is not defined
x = new Date(elem.date); 出错
我明白为什么我会收到错误,但我不知道如何解决它。请帮忙!
【问题讨论】:
-
第一个代码示例与第二个有什么关系?看来
elem不在范围内 -
x = new Date(elem.date);在代码中相对于 $.getJSON 调用的位置在哪里?最简单的解决方案可能是将创建日期的东西转换为可以从 getJSON 中调用的函数。请记住,您还需要访问过滤器。 -
我知道它不在范围内,但考虑到我在这么多函数中使用它,有没有办法在范围外使用变量?
-
@Shilly 我该怎么做?
-
你可以,因此我们询问它在代码中的位置,因此我们知道哪些变量必须在哪里可用。但这只是不太理想的结构。
标签: javascript jquery json function scope