我在我正在处理的应用程序中编写了以下变量声明
var $currentPage = $(".js-page")
$form = $("#new_location"),
$body = $("body"),
$submit = $form.find(".js-submit"),
$elevationAngleKnob = $(".js-knob-elevation-angle"),
$sunbathingTimeKnob = $(".js-knob-sunbathing-time"),
$sunbathingStartKnob = $(".js-knob-sunbathing-start"),
$sunbathingEndKnob = $(".js-knob-sunbathing-end"),
$currentTimeKnob = $(".js-knob-current-time"),
$nearestTimeKnob = $(".js-knob-nearest-time"),
$editLocationForms = $(".edit_location");
如果我不以逗号结束声明的第一行,代码就可以正常工作。
如果我用逗号结束第一行(人们可能认为这是正确的),那么我会得到这个奇怪的错误:
Uncaught ReferenceError: $elevationAngleKnob is not defined
您认为问题出在哪里?
最佳答案
我怀疑您正在尝试在与这些变量声明不同的函数中使用$elevationAngleKnob
。当您在第一行末尾添加逗号时,所有这些变量都是局部变量,如果您尝试在另一个函数中访问它们,您将收到错误。如果没有逗号,自动分号插入会将其更改为:
var $currentPage = $(".js-page");
$form = $("#new_location"),
$body = $("body"),
$submit = $form.find(".js-submit"),
$elevationAngleKnob = $(".js-knob-elevation-angle"),
$sunbathingTimeKnob = $(".js-knob-sunbathing-time"),
$sunbathingStartKnob = $(".js-knob-sunbathing-start"),
$sunbathingEndKnob = $(".js-knob-sunbathing-end"),
$currentTimeKnob = $(".js-knob-current-time"),
$nearestTimeKnob = $(".js-knob-nearest-time"),
$editLocationForms = $(".edit_location");
这将 $currentPage
声明为局部变量,其他所有内容都是对全局变量的赋值,并以逗号运算符分隔。
关于javascript - 在多行变量声明的第一行末尾写入逗号会在 Javascript 中引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665591/