SyntaxError 的原因:基于字符串长度的 JavaScript 条件语句中的意外标识符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18990219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The cause of SyntaxError: Unexpected identifier in a JavaScript conditional statement based on the length of a string
提问by Danny_Student
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: Unexpected identifier
I've tried to add square brackets to var myName = "Mark"; but it didn't help.
我试图在 var myName = "Mark"; 中添加方括号。但它没有帮助。
回答by weeska
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 块中,您的第一个语句是错误的。您必须使用 + 连接要打印的参数:
console.log("Variable consists of" + myName.length);