【发布时间】:2019-10-21 01:34:24
【问题描述】:
我正在尝试创建一个辅助函数,该函数部分接受一个全局变量以进行重新分配。尽量避免使用 eval 来完成这项工作。
let oneQuestionCount,
twoQuestionCount,
oneQuestionsChecked,
twoQuestionsChecked;
function hideFadeIn(divToHide, divToShow, countItem = null, checkedItem = null) {
$("div#item-" + divToHide).hide();
$("div#item-" + divToShow).fadeIn();
if (countItem) {
countItem = $("div#item-" + divToShow + " :input").length; // want the global var to be changed not the function scope var
}
if (checkedItem) {
checkedItem = $("div#item-" + divToHide + " :checked").length; // want the global var to be changed not the function scope var
}
hideFadeIn(
"one",
"two",
twoQuestionCount, // how to pass in and change globally?
oneQuestionsChecked // how to pass in and change globally?
);
console.log(twoQuestionCount, oneQuestionsChecked); // should be reassinged value by the function.
会有多个函数调用和其他需要分配的全局变量——因此是辅助函数。例如: hideFadeIn("one","two",twoQuestionCount, oneQuestionsChecked);然后 hideFadeIn("two","three",threeQuestionCount, twoQuestionsChecked);然后 hideFadeIn("三","四",threeQuestionCount,fourQuestionsChecked);等等……
【问题讨论】:
-
所以,鉴于它们是 global 并且您可以在不传递它们的情况下更改它们..... 为什么?
-
Bc 我需要传递很多问题,而不仅仅是 1 或 2。
-
Noooo.... 它们是全球性的。你明白全球意味着什么,是吗?否则,您需要更清楚地解释问题所在。因为按照目前的写法,听起来您正在尝试解决一个自我强加的问题。
-
是的,我愿意,但我需要传递指针以进行重新分配。由于我将对该函数进行大量调用,因此我需要一种方法来关闭要定位的 GV。所以,我可以传递文本,然后将它评估到 GV 的指针中,或者我试图将 GV 引用传递给函数。例如: hideFadeIn("one","two",twoQuestionCount, oneQuestionsChecked);然后 hideFadeIn("two","three",threeQuestionCount, twoQuestionsChecked);然后 hideFadeIn("三","四",threeQuestionCount,fourQuestionsChecked);等等……
-
然后把你的变量结构改成 T.J.有他的答案,所以你避免
eval()。如果他的示例中的whatever是全局的,您仍然不必将其传递给方法。
标签: javascript jquery variables functional-programming