The cause of SyntaxError: Unexpected identifier in a JavaScript conditional statement based on the length of a string

时间:2021-09-28 22:21:13

I've created a simple if/else statement like so :

我创建了一个简单的if / else语句,如下所示:

var myName = ["Mark"];

if myName.length <= 3;

{

    console.log("It's not true");

}
else 
{

    console.log("Variable consists of" myName.length);
    console.log("I finished my first course".substring(0,26));

}

Unfortunately, the console returns this error : SyntaxError: Unexpected identifier

不幸的是,控制台返回此错误:SyntaxError:意外的标识符

I've tried to add square brackets to var myName = "Mark"; but it didn't help.

我试图在var myName =“Mark”中添加方括号;但它没有帮助。

1 个解决方案

#1


5  

With

var myName = ["Mark"] 

you are assiging an array to the myName, which is not what you want in this case:

你正在为myName分配一个数组,在这种情况下你不是你想要的:

var myName = "Mark"

You have to use parentheses around the if-condition. Also the semicolon is wrong:

你必须在if条件周围使用括号。分号也是错误的:

if (myName.length <= 3){
     ...
}

In the else-block you've got the first statement wrong. You have to use + to concatenate the arguments that you want to print:

在else-block中,你的第一个语句是错误的。您必须使用+来连接要打印的参数:

console.log("Variable consists of" + myName.length);

#1


5  

With

var myName = ["Mark"] 

you are assiging an array to the myName, which is not what you want in this case:

你正在为myName分配一个数组,在这种情况下你不是你想要的:

var myName = "Mark"

You have to use parentheses around the if-condition. Also the semicolon is wrong:

你必须在if条件周围使用括号。分号也是错误的:

if (myName.length <= 3){
     ...
}

In the else-block you've got the first statement wrong. You have to use + to concatenate the arguments that you want to print:

在else-block中,你的第一个语句是错误的。您必须使用+来连接要打印的参数:

console.log("Variable consists of" + myName.length);