【问题标题】:Unexpected identifier?意外的标识符?
【发布时间】:2015-09-14 00:57:52
【问题描述】:

我在这一行遇到了一个意外的标识符错误:

If userInput <= 7

我真的是新手,我不明白这意味着什么。我是 javascript 新手,但我正在学习。我不知道还能说什么,因为我的编程知识一点都不好。

<html>
<body>
<script type="text/javascript">

   // Declare Constants and Variables
   var stateTax;
   var userInput;
   var finalTax;
   var BR = "</br >"; // Line break
   var ES = " ";  // Empty string
   // Welcome user 
   document.write("Welcome to Sales Tax Calculator" + BR);
   document.write("This program calculates sales tax");
   document.write("under $1.00");
   // take user input
   userInput = Prompt("Please enter a number(Cents)" + ES);

   // call selection structure
   If userInput <= 7 then
   stateTax = 0; 

   else if userInput <= 21 then
   stateTax = 1;

   else if userInput <= 35 then
   stateTax = 2 ;

   else if userInput <= 49 then
   stateTax = 3; 

   else if userInput <= 64 then
   stateTax = 4;

   else if userInput <= 78 then
   stateTax = 5;

   else if userInput <= 92 then
   stateTax = 6;

   else if userInput <= 99 then 
   stateTax = 7;

   else if userInput > 99 then
   document.write("Error, Please enter a value less than 99!");
   end if

   // Calculate and Display sales tax
   finalTax = userInput * stateTax;

   document.write("Sales tax equals: " + finalTax);
   document.write("Thank you for using tax calculator");
</script>
</body>
</html>

【问题讨论】:

标签: javascript syntax-error


【解决方案1】:

您的代码中有几个语法问题。您可以做的一件事是转到jshint.com 并将您的代码粘贴到其中。然后它将向您显示许多常见错误。有些错误可能会令人困惑,但我认为总体而言,它的帮助多于伤害。或者,使用具有 javascript linting 的编辑器,以消除潜在的错误。

您的代码中的一些特定语法错误:

  • Prompt() 中的“p”必须小写(javascript 区分大小写)
  • If 中的“i”必须小写。
  • 您必须将条件放在括号中的 if 关键字之后(例如,if (userInput &lt;= 7) {
  • 您不能使用then 标记代码块的开头。而是使用“{”。也可以使用“}”来标记代码块的结束,而不是像endif这样的关键字

例如,这段代码

If userInput <= 7 then
stateTax = 0; 
else if userInput <= 21 then

应该是这样的

if (userInput <= 7) {
    stateTax = 0;
} else if (userInput <= 21) {

附带说明,如果条件块中只有一个语句,则括号是可选的,但我强烈建议始终包含括号以避免以后维护代码时出现问题。此外,您可以使用任何您想要的缩进,我只使用了 4 个空格,因为这是我发现的开源代码中最常见的样式。

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2020-07-10
    • 2012-06-19
    • 2014-04-10
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多