【问题标题】:Pass a global variable to a function for reassignment in javascript将全局变量传递给函数以在 javascript 中重新分配
【发布时间】: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


【解决方案1】:

你不能那样做。当您将twoQuestionCount 传递给hideFadeIn 时,传递的是它的,而不是变量。

如果你愿意,你可以把它们放在一个对象中,然后传入这个对象:

let whatever = {
    oneQuestionCount: 0,
    twoQuestionCount: 0,
    oneQuestionsChecked: 0,
    twoQuestionsChecked: 0
};

然后

hideFadeIn("one", "two", whatever);

hideFadeIn 可以更改它接收到的对象的属性。

【讨论】:

    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 2016-06-25
    • 2013-02-09
    • 1970-01-01
    • 2020-07-06
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多