最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - SyntaxError: missing ; before statementExpected ';' and instead saw '[' - Stack Ove

programmeradmin0浏览0评论

This is part of my code that deposes a sentence into word values of an array:

//var sentence = document.forms["chatForm"]["chat"].value;
var sentence = ";Hey, this is a sentence!"; //Example
var preMsg,msg = sentence.toLowerCase().match(/[\w'-;]+/g);
var msg[0] = msg[0].replace(/^;/, '');
if (msg[0] !== preMsg[0]) { //Checks if semi-colon was removed
    msg.unshift("hooray");
    alert(msg[0]+" "+msg[1]); //Testing
}

What I get from JSLint:

Expected ';' and instead saw '['.

var msg[0] = msg[0].replace(/^;/, '');

The console gives me this error for the same line of code: SyntaxError: missing ; before statement

I'm just beginning to learn JavaScript, and I don't know what is wrong with that line.

This is part of my code that deposes a sentence into word values of an array:

//var sentence = document.forms["chatForm"]["chat"].value;
var sentence = ";Hey, this is a sentence!"; //Example
var preMsg,msg = sentence.toLowerCase().match(/[\w'-;]+/g);
var msg[0] = msg[0].replace(/^;/, '');
if (msg[0] !== preMsg[0]) { //Checks if semi-colon was removed
    msg.unshift("hooray");
    alert(msg[0]+" "+msg[1]); //Testing
}

What I get from JSLint:

Expected ';' and instead saw '['.

var msg[0] = msg[0].replace(/^;/, '');

The console gives me this error for the same line of code: SyntaxError: missing ; before statement

I'm just beginning to learn JavaScript, and I don't know what is wrong with that line.

Share Improve this question asked Dec 13, 2013 at 2:22 DimittoDimitto 832 silver badges8 bronze badges 7
  • 1 preMsg is always undefined in your code. var preMsg,msg = 42; doesn't mean both variables will have value 42. – zerkms Commented Dec 13, 2013 at 2:26
  • @zerkms Is there a way to do something like that? Or do I just have to do "var preMsg = msg"? – Dimitto Commented Dec 13, 2013 at 2:32
  • [\w'-;] probably doesn't do what you expect. It will match word character, or any ASCII character between apostrophe (x27) and semicolon (x3B), which includes mas and periods. – p.s.w.g Commented Dec 13, 2013 at 2:32
  • @p.s.w.g I'm fairly sure it does. It wasn't outputting semi-colons until I added that to the list. – Dimitto Commented Dec 13, 2013 at 2:38
  • @Dimitto: yep, just another explicit assignment – zerkms Commented Dec 13, 2013 at 2:40
 |  Show 2 more ments

2 Answers 2

Reset to default 4

[ is not a valid character for a variable name, and the line

var msg[0] = msg[0].replace(/^;/, '');

is declaring a new variable named "msg[0]", you just need to remove var and change it to:

msg[0] = msg[0].replace(/^;/, '');

You want just msg[0] = ...

var is for declaring variables!

发布评论

评论列表(0)

  1. 暂无评论