我正在尝试创建一个辅助函数,该函数部分接受全局变量以进行重新分配。试图避免使用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(“一个”,“两个”,twoQuestionCount,一个问题已检查);然后hideFadeIn(“ two”,“ three”,threeQuestionCount,twoQuestionsChecked);然后hideFadeIn(“三个”,“四个”,三个问题计数,四个问题选中);等等...
答案 0 :(得分:2)
您不能那样做。当您将twoQuestionCount
传递到hideFadeIn
时,将传递其值,而不是变量。
如果愿意,可以将它们放在一个对象中,然后传递该对象:
let whatever = {
oneQuestionCount: 0,
twoQuestionCount: 0,
oneQuestionsChecked: 0,
twoQuestionsChecked: 0
};
然后
hideFadeIn("one", "two", whatever);
hideFadeIn
可以更改其接收的对象的属性。