简体   繁体   English

将全局变量传递给函数以在JavaScript中进行重新分配

[英]Pass a global variable to a function for reassignment in javascript

I am trying to create a helper function that in part takes in a global variable for reassignment. 我正在尝试创建一个辅助函数,该函数部分接受全局变量以进行重新分配。 Trying to avoid using eval to make this work. 尝试避免使用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.

There will be multiple function calls and other global variables that need to be assigned - hence the helper function. 将需要分配多个函数调用和其他全局变量-因此需要辅助函数。 ex: hideFadeIn("one","two",twoQuestionCount, oneQuestionsChecked); 例如:hideFadeIn(“一个”,“两个”,twoQuestionCount,一个问题已检查); then hideFadeIn("two","three",threeQuestionCount, twoQuestionsChecked); 然后hideFadeIn(“ two”,“ three”,threeQuestionCount,twoQuestionsChecked); then hideFadeIn("three","four",threeQuestionCount, fourQuestionsChecked); 然后hideFadeIn(“三个”,“四个”,三个问题计数,四个问题选中); etc... 等等...

You can't do that. 你不能那样做。 When you pass twoQuestionCount into hideFadeIn , its value is passed, not the variable. 当您将twoQuestionCount传递给hideFadeIn ,将传递其 ,而不是变量。

If you like, you could put those in an object, and then pass in the object: 如果愿意,可以将它们放在一个对象中,然后传递该对象:

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

then 然后

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

hideFadeIn can change the properties on the object it receives. hideFadeIn可以更改其接收的对象的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM