不知道为什么语法错误")"javascript

Not sure why syntax error ")" javascript

本文关键字:quot javascript 为什么 语法 不知道 错误      更新时间:2023-09-26

我正在尝试创建一个运行while循环的函数。

它应该运行以下命令:

  1. 当循环中的数字是3的倍数时,将参数string1附加到div
  2. 当循环中的数字是5的倍数时,将参数string2附加到div
  3. else,在
  4. 下面追加另一个字符串。

我得到Chrome工具箱错误"Uncaught SyntaxError: Unexpected token)"在脚本标签开始的行"for (x % 3 == 0){"。不知道为什么…

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="output"></div>

    <script src="https://code.jquery.com/jquery-2.1.1.js"></script>
    <script>
    var this_that = function(string1, string2) {
      var x = 1
      while (x <= 100) {
        for (x % 3 == 0) {
        $(#output).append(x, string1)
      } else if (x % 5 == 0) {
        $(#output).append(x, string2)
      } else {
        $(#output).append(x,'is not a multiple of 3 or 5')
      }
      x++
    }
  }


</script>

您的for应该是这里的if:

for (x % 3 == 0) {
应:

if (x % 3 == 0) {

这个for (x % 3 == 0)应该像这个if (x % 3 == 0)

你只是检查一个条件,如果x是3的倍数并且你不想迭代一些语句块,这是for语句的目的。

对于您得到的错误,这是由for语句的错误语法引起的。正确的语法如下:

for ([initialization]; [condition]; [final-expression])
   statement

关于For语句的更多文档,请查看这里

使用以下

var this_that = function(string1, string2) {
var x = 1;
while (x < 100) {
    if (x % 3 === 0) {
        $(#output).append(x, string1)
    } else if (x % 5 == 0) {
        $(#output).append(x, string2)
    } else {
        $(#output).append(x, 'is not a multiple of 3 or 5')
    }
    x++
}
}

为什么使用for ?

for (x % 3 == 0) //problem lies here. It should be if(x % 3 == 0)
{
        $(#output).append(x, string1)
} 
else if (x % 5 == 0) //if statement never started, then how can we have else if
{
   $(#output).append(x, string2)
} 
else 
{
   $(#output).append(x,'is not a multiple of 3 or 5')
}

如果您不想进行初始化和递增,则必须在条件之前和之后给出分号for(;x%3==0;)

其次,你使用else而不使用if,所以使用if(x%3==0)

希望有帮助!

代码中的各种错误

  1. 您需要将选择器字符串包装为$('#output')
  2. 检查条件需要使用if, for使用For loop

var this_that = function(string1, string2) {
  var x = 1,
    op = $('#output');
  while (x <= 100) {
    if (x % 3 == 0) {
      op.append(x, ' is a multiple of 3 <br>');
    } else if (x % 5 == 0) {
      op.append(x, ' is a multiple of 5<br>');
    } else {
      op.append(x, ' is not a multiple of 3 or 5<br>');
    }
    x++;
  }
}
this_that();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="output"></div>

除了其他答案之外,您的选择器上还缺少引号

var this_that = function(string1, string2) {
      var x = 1
      if (x <= 100) {
        for (x % 3 == 0) {
        $('#output').append(x, string1)
      } else if (x % 5 == 0) {
        $('#output').append(x, string2)
      } else {
        $('#output').append(x,'is not a multiple of 3 or 5')
      }
      x++
    }
  }