Ошибка предполагается наличие идентификатора строки или числа

Случаи возникновения ошибки в IE: "Предполагается наличие идентификатора, строки или числа" (Expected identifier, string...) Разбираемся отчего может возникать ошибка только в Internet Explorer:  «Предполагается наличие идентификатора, строки или числа» (Expected identifier, string or number).

Рассмотрим код в котором возникает ошибка. Причём ошибка только в браузере IE (у меня IE8), в остальных браузерах с этим нормально.

Неправильно:

...
delete : function() {   // delete в кавычках, чтобы работало в IE!
               if(confirm('Совсем-совсем удалить эту запись?')) {
...
                  delEvent(calEvent); // удаляем из БД при редактировании
                  $dialogContent.dialog("close");
                  }
},
cancel : function() {
$dialogContent.dialog("close");
}, // <-- здесь не должно быть запятой
}
	        }).show();

Это первый случай ошибки, который много где уже описан. Когда заканчивается перечисление переменных, то после последнего элемента не нужно ставить запятую. Internet Explorer считает это ошибкой и вообще не будет выполнять весь код, не откроет сайт (календарь FullCalendar в моём случае).

Но даже удалив запятую, ошибка не исчезнет. Именно этот случай у меня и возник (запятую ткнул для общности решения проблемы). При просмотре текста ошибки:

Error: Предполагается наличие идентификатора, строки или числа ( Expected identifier, string or number” )

Оказывается в браузере Internet Explorer слово delete — зарезервированное слово и просто так вводить переменную delete нельзя. Решение проблемы: заключить в одинарные кавычки, вот так — ‘delete’.

Правильный код, который будет работать в IE:

...
'delete' : function() {   // delete в кавычках, чтобы работало в IE!
               if(confirm('Совсем-совсем удалить эту запись?')) {
...
                  delEvent(calEvent); // удаляем из БД при редактировании
                  $dialogContent.dialog("close");
                  }
},
cancel : function() {
$dialogContent.dialog("close");
}
}
       }).show();

stackoverflow.com — это очень толковый и крупный ресурс, лично я решил с его помощью около 70-80% всех своих косяков, хотя сначала не верил в его силу; только придётся перевести проблему и сформулировать на английском.

———————-

Using the word class as a key in a Javascript dictionary can also trigger the dreaded «Expected identifier, string or number» error because class is a reserved keyword in Internet Explorer.

BAD

{ class : 'overlay'} // ERROR: Expected identifier, string or number

GOOD

{'class': 'overlay'}

When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.

Hope this hint saves you a day of debugging hell.

————————

А здесь можно видеть список зарезервированных слов, чтобы уже не натыкаться (как видим save и close сюда не входят, поэтому их можем не брать в кавычки).

Список зарезервированных переменных для JavaScript, избегайте называть переменные зарезервированными словами!

abstract   else   instanceof   super  
boolean   enum   int   switch  
break   export   interface   synchronized  
byte   extends   let   this  
case   false   long   throw  
catch   final   native   throws  
char   finally   new   transient  
class   float   null   true  
const   for   package   try  
continue   function   private   typeof  
debugger   goto   protected   var  
default   if   public   void  
delete   implements   return   volatile  
do   import   short   while  
double   in   static   with  

Содержание

  1. Случаи возникновения ошибки в IE: «Предполагается наличие идентификатора, строки или числа» (Expected identifier, string. )
  2. How to Fix Java Error – Identifier Expected
  3. What’s the meaning of Identifier Expected error?
  4. How to Fix it
  5. Another example
  6. Conclusion
  7. Application Development
  8. Pages
  9. Search This Blog
  10. Sunday, November 25, 2007
  11. Expected identifier, string or number
  12. 61 comments:

Случаи возникновения ошибки в IE: «Предполагается наличие идентификатора, строки или числа» (Expected identifier, string. )

Рассмотрим код в котором возникает ошибка. Причём ошибка только в браузере IE (у меня IE8), в остальных браузерах с этим нормально.

Это первый случай ошибки, который много где уже описан. Когда заканчивается перечисление переменных, то после последнего элемента не нужно ставить запятую. Internet Explorer считает это ошибкой и вообще не будет выполнять весь код, не откроет сайт (календарь FullCalendar в моём случае).

Но даже удалив запятую, ошибка не исчезнет. Именно этот случай у меня и возник (запятую ткнул для общности решения проблемы). При просмотре текста ошибки:

Error: Предполагается наличие идентификатора, строки или числа ( Expected identifier, string or number” )

Оказывается в браузере Internet Explorer слово delete — зарезервированное слово и просто так вводить переменную delete нельзя. Решение проблемы: заключить в одинарные кавычки, вот так — ‘delete’.

Правильный код, который будет работать в IE:

Using the word class as a key in a Javascript dictionary can also trigger the dreaded «Expected identifier, string or number» error because class is a reserved keyword in Internet Explorer.

When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.

Hope this hint saves you a day of debugging hell.

А здесь можно видеть список зарезервированных слов, чтобы уже не натыкаться (как видим save и close сюда не входят, поэтому их можем не брать в кавычки).

Список зарезервированных переменных для JavaScript, избегайте называть переменные зарезервированными словами!

abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
catch final native throws
char finally new transient
class float null true
const for package try
continue function private typeof
debugger goto protected var
default if public void
delete implements return volatile
do import short while
double in static with

almix
Разработчик Loco, автор статей по веб-разработке на Yii, CodeIgniter, MODx и прочих инструментах. Создатель Team Sense.

Источник

How to Fix Java Error – Identifier Expected

Posted by Marta on November 21, 2021 Viewed 88443 times

In this article you will learn how to fix the java error: identifier expected to get a better understanding of this error and being able to avoid in the future.

This error is a very common compilation error that beginners frequently face when learning Java. I will explain what is the meaning of this error and how to fix it.

Table of Contents

What’s the meaning of Identifier Expected error?

The identifier expected error is a compilation error, which means the code doesn’t comply with the syntax rules of the Java language. For instance, one of the rules is that there should be a semicolon at the end of every statement. Missing the semicolon will cause a compilation error.

The identifier expected error is also a compilation error that indicates that you wrote a block of code somewhere where java doesn’t expect it.

Here is an example of piece of code that presents this error:

If you try to compile this class, using the javac command in the terminal, you will see the following error:

Output:

This error is slightly confusing because it seems to suggest there is something wrong with line 2. However what it really means is that this code is not in the correct place.

How to Fix it

We have seen what the error actually means, however how could I fix it? The error appears because I added some code in the wrong place, so what’s the correct place to right code? Java expects the code always inside a method. Therefore, all necessary to fix this problem is adding a class method and place the code inside. See this in action below:

The code above will compile without any issue.

Another example

Here is another example that will return the identifier expected error:

Output:

As before, this compilation error means that there is a piece of code: e.print() that is not inside a class method. You might be wondering, why line 7 ( Example e = new Example(); ) is not considered a compilation error? Variable declarations are allowed outside a method, because they will be considered class fields and their scope will be the whole class.

Here is a possible way to fix the code above:

The fix is simply placing the code inside a method.

Conclusion

To summarise, this article covers how to fix the identifier expected java error. This compilation error will occur when you write code outside a class method. In java, this is not allow, all code should be placed inside a class method.

In case you want to explore java further, I will recommend the official documentation

Hope you enjoy the tutorial and you learn what to do when you find the identifier expected error. Thanks for reading and supporting this blog.

Источник

Application Development

Web application Sharing including ASP, ASP.NET 1.0 (C#) AND ASP.NET 2.0 (C#) MS SQL 2005 Server, Life, Travelling

Pages

Search This Blog

Sunday, November 25, 2007

Expected identifier, string or number

For below javascript code, i got error «Expected identifier, string or number» in IE but it’s working fine in firefox and safari.
var RealtimeViewer =
<
timer : 5000,
Interval : null,

init: function() <
xxxxxxxxx
xxxxxxxxx
>,
RatingUpdate: function() <
xxxxxxxx
xxxxxxxx
> ,
>;
To solve the problem, remove the last «,» before close the object RealtimeViewer «>;«. It will become

var RealtimeViewer = <
timer : 5000,
Interval : null,

init: function()
<
xxxxxxxxx
xxxxxxxxx
>,

RatingUpdate: function()
<
xxxxxxxx
xxxxxxxx
>
>;

mate. you just solved a problem I’d spent two days working on. Champ!

Same here!!
I think it’s dumb that IE assumes a new string just because you had a comma, but THANK YOU for sharing the solution!!

Dang. I can’t believe it consumed me. and it was so simple!! GAHH 😐

Thank You. Thank You. Thank You.

lol, that was so simple, hahaha

thank you! luckily for me (and others, it appears), this entry is the first hit on google when you search «expected identifier string number»

Thanks , that was a great help.

Thank you so much, you just saved me hours of pain.

Thanks so much! You just saved me hours of debugging.

Wow. first result on google and my problem is solved (even though its unrelated, it was that stupid comma)

Im getting same error in prototype.js but didnt get «,» before closing last >. Do you have any idea about that.

Hi Amit, can post ur code to me? thanks

I have solved that problem. Problem was not with prototype.js but with another js file.

Another mind brought back from the edge of IE-induced insanity. Thank you!

Thank you. It helped a lot. While trying to debug the problem, i never did even had a hint that it would be because of a this :-s

thank you. 🙂 stupid internet explorer is driving me crazy. thank you again for sharing this extremely quick fix!

Nice thanks a lot firstr search in google and its solved , sounds amazing

Man, youre the king!

This weird messege is also caused by an ending comma in an json feed!

Behold my brothers and sisters.

Never again will you suffer at the hands of such a simple mistake.

Great Catch! Also I notice that using reserved words as method names will produce the same error (at least when constructing classes in mootools). So for example.

var MyClass = new Class(<

Thanks for posting the fix.

thanks a lot.
simple and effective solution..

Thanks man. lifesaver!

Now if only I could get jwplayer to work in IE.

I feel so stupid but thank you so much — if only I had thought to remove the last comma 2 hours ago!

Tanks mate! I will now be able to brag with my error free site!

Thanks a lot! This saved me lots of frustration!

Nice simple solution — hard part for me is finding where the stupid error comes from in the first place! The IE dialog box tells the line number and character position but remember this is the line relative to the JS file being executed.

Well, you didn’t save the the «hours of pain,» but I’ll still give you the thanks!

OMFG, if IE just specified which GD file it thought the error was in, I’d be gulping cervezas by now. Ugh.

God I hate trying to write JS for IE. You’re my hero

Thanks for this explanation, it saved me some time!

Please don’t ever take down this post! You saved the last shreds of my sanity 🙂
Stupid IE. I don’t even care that it caused an error in the lame-@ss browser. why can’t they provide an error message that actually means something.

you saved the day.. Thanx.

I just ran into this myself, and your post was exceedingly helpful. Thanks!

Thank God this is the first entry on Google! and thank God you put up this post 🙂

ty, i was freaked out when it didn’t work in ie and glad when it turned out to be such a simple fix.

Thank you for the fix. Googled the IE error and BLAME!
Can’t thank you enough.
Thank you. Thank you.

2 years after posting this article, its still helping people out.

Thanks for the info — and for potentially saving me hours of debugging (which with IE is like p*ssing in the dark).

Thank you.
Its a simple problem, but solution is not so obvious. 😉

Thanks this really helped out.

brilliant!
i cannot thank you enough!

Thanks a lot for sharing this. That saved me a lot!
Isaac

Thank You! Thank You! I already hate IE, but you saved me from cursing it even more.

Thank you so much, please leave this thread up as long as possible, it saved my ass!

DAAAANG. I can’t believe that was it.

Thank you for sharing this.

Now i’m no IE fan. and gawd knows I love bashing it, but if there are no more params then the last , is not needed, and is in fact wrong!

IE 6 rage alert. hehehe
Thanx for the heads up! Pointed me right at the b@stard extra comma!

thanks very very useful

THANK YOU!! I spent *hours* trying to figure out why IE was throwing this exact error in a jQuery statement. It turns out the cause is the same, although in this particular case it was in an ajax list of key/value pairs. The last key/value pair ended with an extra comma. Removing it was the fix. Thanks again for posting this!

Thanks!! Would have never figured this out on my own. It’s always IE, even with IE 6 phasing out, it’s still always IE!!

What ever would we do without Google… and the good souls who post their solutions for the rest of us. I hadn’t yet spent hours trying to figure this out, but I’m sure I would have. Many thanks!!

BTW if anyone else has this problem while trying to configure CKEDITOR (I’ve been pulling my hair 🙂

As of 1/13/2011 the online document at http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html has a long list of example config statements, and many do not enclose the reserved word class in apostrophes, which results in this SAME ERROR MESSAGE. So if you copy from that documentation, you need to update the code to ‘class’ (see comment from Hans on Feb 09 in this forum.)

Saved my butt thank you!

If anyone is configuring JWPlayer and is using the Google Analytics Plugin — beware if it is the last line:

Which should be of course:

Crazy thing is that it works fine in FireFox, Safari, IE9 . but not IE8 so it took me a while to catch.

How do they manage to do this STILL at Microsoft?

Thanks soooo much for posting this.

thanks Gabrielle, for sharing your experience here.

Super dooper dooper. Man why did they even build an IE. Please ask the microsoft guys to just buy of firefox and stop creating IE browsers any more.

This is insane. Who puts extra comma before ending a bracket? «>»

there must be something wrong with firefox and safari that do not have problem with that.

Источник

На чтение 4 мин. Опубликовано 15.12.2019

В старом блоге была заметка с точно таким же заголовком и аналогичной смысловой нагрузкой. Я подумал, что нет никакого резона переносить ее в новый блог, слишком уж сомнительной, как мне казалось, была ее ценность.

Тем не менее, время от времени натыкаюсь на скрипты, где расставлены все те же грабли. Ситуация приобретает особый шарм, если содержащее ошибку приложение пропущено через компрессор и несжатые исходники отсутствуют.

Ошибка: Error: Expected identifier, string or number

Данная ошибка возникает в том случае, если в перечислении свойств объекта присутствует лишняя запятая — после последнего свойства. JavaScript движок в IE 7 (и ниже) считает, что не задано наименование следующего свойства объекта. Ситуация усугубляется тем, что при возникновении такой ошибки прекращается обработка всех JS скриптов на странице.

Ошибку вызовет вот такой код:

Как показывает опыт, чаще всего она допускается при перечислении свойств плагинов популярных JavaScript фреймворков. В предыдущей заметке я приводил пример, в котором фигурирует jQuery:

В обоих примерах, если убрать последнюю запятую в списке свойств, ошибка «Expected identifier, string or number» исчезнет.

Рассмотрим код в котором возникает ошибка. Причём ошибка только в браузере IE (у меня IE8), в остальных браузерах с этим нормально.

Это первый случай ошибки, который много где уже описан. Когда заканчивается перечисление переменных, то после последнего элемента не нужно ставить запятую. Internet Explorer считает это ошибкой и вообще не будет выполнять весь код, не откроет сайт (календарь FullCalendar в моём случае).

Но даже удалив запятую, ошибка не исчезнет. Именно этот случай у меня и возник (запятую ткнул для общности решения проблемы). При просмотре текста ошибки:

Error: Предполагается наличие идентификатора, строки или числа ( Expected identifier, string or number” )

Оказывается в браузере Internet Explorer слово delete — зарезервированное слово и просто так вводить переменную delete нельзя. Решение проблемы: заключить в одинарные кавычки, вот так — ‘delete’.

Правильный код, который будет работать в IE:

Using the word class as a key in a Javascript dictionary can also trigger the dreaded «Expected identifier, string or number» error because class is a reserved keyword in Internet Explorer.

When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.

Hope this hint saves you a day of debugging hell.

А здесь можно видеть список зарезервированных слов, чтобы уже не натыкаться (как видим save и close сюда не входят, поэтому их можем не брать в кавычки).

Список зарезервированных переменных для JavaScript, избегайте называть переменные зарезервированными словами!

abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
catch final native throws
char finally new transient
class float null true
const for package try
continue function private typeof
debugger goto protected var
default if public void
delete implements return volatile
do import short while
double in static with

almix
Разработчик Loco, автор статей по веб-разработке на Yii, CodeIgniter, MODx и прочих инструментах. Создатель Team Sense.

I have an object like;

and when i run my page in IE8 standards its giving me the following error;

SCRIPT1028: Expected identifier, string or number

and points to the line : class:’ ‘,

can anyone please tell me why i cant use this for IE? is it a reserved word or something?

4 Answers 4

You need to add quotes round the class which is a reserved word. Please also note, that you should remove the last comma:

Случаи возникновения ошибки в IE: "Предполагается наличие идентификатора, строки или числа" (Expected identifier, string...) Разбираемся отчего может возникать ошибка только в Internet Explorer:  «Предполагается наличие идентификатора, строки или числа» (Expected identifier, string or number).

Рассмотрим код в котором возникает ошибка. Причём ошибка только в браузере IE (у меня IE8), в остальных браузерах с этим нормально.

Неправильно:

...
delete : function() {   // delete в кавычках, чтобы работало в IE!
               if(confirm('Совсем-совсем удалить эту запись?')) {
...
                  delEvent(calEvent); // удаляем из БД при редактировании
                  $dialogContent.dialog("close");
                  }
},
cancel : function() {
$dialogContent.dialog("close");
}, // <-- здесь не должно быть запятой
}
	        }).show();

Это первый случай ошибки, который много где уже описан. Когда заканчивается перечисление переменных, то после последнего элемента не нужно ставить запятую. Internet Explorer считает это ошибкой и вообще не будет выполнять весь код, не откроет сайт (календарь FullCalendar в моём случае).

Но даже удалив запятую, ошибка не исчезнет. Именно этот случай у меня и возник (запятую ткнул для общности решения проблемы). При просмотре текста ошибки:

Error: Предполагается наличие идентификатора, строки или числа ( Expected identifier, string or number” )

Оказывается в браузере Internet Explorer слово delete — зарезервированное слово и просто так вводить переменную delete нельзя. Решение проблемы: заключить в одинарные кавычки, вот так — ‘delete’.

Правильный код, который будет работать в IE:

...
'delete' : function() {   // delete в кавычках, чтобы работало в IE!
               if(confirm('Совсем-совсем удалить эту запись?')) {
...
                  delEvent(calEvent); // удаляем из БД при редактировании
                  $dialogContent.dialog("close");
                  }
},
cancel : function() {
$dialogContent.dialog("close");
}
}
       }).show();

stackoverflow.com — это очень толковый и крупный ресурс, лично я решил с его помощью около 70-80% всех своих косяков, хотя сначала не верил в его силу; только придётся перевести проблему и сформулировать на английском.

———————-

Using the word class as a key in a Javascript dictionary can also trigger the dreaded «Expected identifier, string or number» error because class is a reserved keyword in Internet Explorer.

BAD

{ class : 'overlay'} // ERROR: Expected identifier, string or number

GOOD

{'class': 'overlay'}

When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.

Hope this hint saves you a day of debugging hell.

————————

А здесь можно видеть список зарезервированных слов, чтобы уже не натыкаться (как видим save и close сюда не входят, поэтому их можем не брать в кавычки).

Список зарезервированных переменных для JavaScript, избегайте называть переменные зарезервированными словами!

abstract   else   instanceof   super  
boolean   enum   int   switch  
break   export   interface   synchronized  
byte   extends   let   this  
case   false   long   throw  
catch   final   native   throws  
char   finally   new   transient  
class   float   null   true  
const   for   package   try  
continue   function   private   typeof  
debugger   goto   protected   var  
default   if   public   void  
delete   implements   return   volatile  
do   import   short   while  
double   in   static   with  

Some users are reporting occasional JS errors on my site. The error message says «Expected identifier, string or number» and the line number is 423725915, which is just an arbitrary number and changes for each report when this occurs.
This mostly happens with IE7/ Mozilla 4.0 browsers.

I scanned my code a bunch of times and ran jslint but it didn’t pick anything up — anyone know of the general type of JS problems that lead to this error message?

asked Jan 27, 2010 at 19:40

psychotik's user avatar

psychotikpsychotik

37.9k34 gold badges100 silver badges135 bronze badges

3

The cause of this type of error can often be a misplaced comma in an object or array definition:

var obj = {
   id: 23,
   name: "test",  <--
}

If it appears at a random line, maybe it’s part of an object defintion you are creating dynamically.

answered Jan 27, 2010 at 19:49

amercader's user avatar

7

Using the word class as a key in a Javascript dictionary can also trigger the dreaded «Expected identifier, string or number» error because class is a reserved keyword in Internet Explorer.

BAD

{ class : 'overlay'} // ERROR: Expected identifier, string or number

GOOD

{'class': 'overlay'}

When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.

Hope this hint saves you a day of debugging hell.

answered Jan 11, 2012 at 5:29

Roy Hyunjin Han's user avatar

Roy Hyunjin HanRoy Hyunjin Han

4,6172 gold badges30 silver badges22 bronze badges

6

Actually I got something like that on IE recently and it was related to JavaScript syntax «errors». I say error in quotes because it was fine everywhere but on IE. This was under IE6. The problem was related to JSON object creation and an extra comma, such as

{ one:1, two:2, three:3, }

IE6 really doesn’t like that comma after 3. You might look for something like that, touchy little syntax formality issues.

Yeah, I thought the multi-million line number in my 25 line JavaScript was interesting too.

Good luck.

answered Jan 27, 2010 at 19:48

cjstehno's user avatar

cjstehnocjstehno

13.3k4 gold badges43 silver badges56 bronze badges

1

This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.

It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.

Here’s a sample web page that will demonstrate this problem in IE:

<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
   var s = document.createElement("script");
   s.setAttribute("type", "text/javascript");
   document.body.appendChild(s);
   s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>

This yielded for me the following error:

Line: 54654408
Error: Object required

answered Jan 27, 2010 at 19:52

ErikE's user avatar

ErikEErikE

48.7k23 gold badges149 silver badges195 bronze badges

1

Just saw the bug in one of my applications, as a catch-all, remember to enclose the name of all javascript properties that are the same as keyword.

Found this bug after attending to a bug where an object such as:

var x = { class: 'myClass', function: 'myFunction'};

generated the error (class and function are keywords)
this was fixed by adding quotes

var x = { 'class': 'myClass', 'function': 'myFunction'};

I hope to save you some time

answered Sep 6, 2013 at 21:26

Josue Alexander Ibarra's user avatar

1

As noted previously, having an extra comma threw an error.

Also in IE 7.0, not having a semicolon at the end of a line caused an error. It works fine in Safari and Chrome (with no errors in console).

answered Aug 11, 2011 at 18:30

B Seven's user avatar

B SevenB Seven

44.2k66 gold badges239 silver badges384 bronze badges

IE7 is much less forgiving than newer browsers, especially Chrome. I like to use JSLint to find these bugs. It will find these improperly placed commas, among other things. You will probably want to activate the option to ignore improper whitespace.

In addition to improperly placed commas, at this blog in the comments someone reported:

I’ve been hunting down an error that only said «Expected identifier»
only in IE (7). My research led me to this page. After some
frustration, it turned out that the problem that I used a reserved
word as a function name («switch»). THe error wasn’t clear and it
pointed to the wrong line number.

answered Aug 13, 2011 at 0:34

Muhd's user avatar

MuhdMuhd

24.1k22 gold badges61 silver badges78 bronze badges

This error occurs when we add or missed to remove a comma at the end of array or in function code. It is necessary to observe the entire code of a web page for such error.

I got it in a Facebook app code while I was coding for a Facebook API.

<div id='fb-root'>
    <script type='text/javascript' src='http://connect.facebook.net/en_US/all.js'</script>
    <script type='text/javascript'>
          window.fbAsyncInit = function() {
             FB.init({appId:'".$appid."', status: true, cookie: true, xfbml: true});            
             FB.Canvas.setSize({ width: 800 , height: 860 , }); 
                                                       // ^ extra comma here
          };
    </script>

indiv's user avatar

indiv

17.3k6 gold badges61 silver badges82 bronze badges

answered Jun 26, 2013 at 9:32

Tousif Jamadar's user avatar

0

This sounds to me like a script that was pulled in with src, and loaded just halfway, causing a syntax error sine the remainder is not loaded.

answered Jan 27, 2010 at 19:44

Roland Bouman's user avatar

Roland BoumanRoland Bouman

31k6 gold badges66 silver badges67 bronze badges

IE7 has problems with arrays of objects

columns: [
{
  field: "id",
  header: "ID"
},
{
  field: "name",
  header: "Name" , /* this comma was the problem*/ 
},
...

answered Feb 5, 2013 at 16:55

Stefan Michev's user avatar

Stefan MichevStefan Michev

4,7773 gold badges35 silver badges30 bronze badges

Another variation of this bug: I had a function named ‘continue’ and since it’s a reserved word it threw this error. I had to rename my function ‘continueClick’

answered Apr 3, 2013 at 19:20

Kevin Audleman's user avatar

Maybe you’ve got an object having a method ‘constructor’ and try to invoke that one.

answered Apr 24, 2014 at 13:49

Niels Steenbeek's user avatar

Niels SteenbeekNiels Steenbeek

4,6822 gold badges40 silver badges50 bronze badges

You may hit this problem while using Knockout JS. If you try setting class attribute like the example below it will fail:

<span data-bind="attr: { class: something() }"></span>

Escape the class string like this:

<span data-bind="attr: { 'class': something() }"></span>

My 2 cents.

answered Jun 11, 2015 at 15:22

iDevGeek's user avatar

iDevGeekiDevGeek

4645 silver badges4 bronze badges

I too had come across this issue. I found below two solutions.
1). Same as mentioned by others above, remove extra comma from JSON object.
2). Also, My JSP/HTML was having . Because of this it was triggering browser’s old mode which was giving JS error for extra comma. When used it triggers browser’s HTML5 mode(If supported) and it works fine even with Extra Comma just like any other browsers FF, Chrome etc.

answered Aug 5, 2015 at 22:55

1

Here is a easy technique to debug the problem:
echo out the script/code to the console.
Copy the code from the console into your IDE.
Most IDE’s perform error checking on the code and highlight errors.
You should be able to see the error almost immediately in your JavaScript/HTML editor.

answered Jan 22, 2016 at 2:57

hisenberg's user avatar

hisenberghisenberg

1301 silver badge5 bronze badges

Had the same issue with a different configuration. This was in an angular factory definition, but I assume it could happen elsewhere as well:

angular.module("myModule").factory("myFactory", function(){
    return
    {
        myMethod : function() // <--- error showing up here
        {
            // method definition
        } 
    }
});

Fix is very exotic:

angular.module("myModule").factory("myFactory", function(){
    return { // <--- notice the absence of the return line
        myMethod : function()
        {
            // method definition
        } 
    }
});

answered Feb 19, 2016 at 9:59

wiwi's user avatar

wiwiwiwi

2702 silver badges9 bronze badges

This can also happen in Typescript if you call a function in middle of nowhere inside a class. For example

class Dojo implements Sensei {
     console.log('Hi'); // ERROR Identifier expected.
     constructor(){}
}

Function calls, like console.log() must be inside functions. Not in the area where you should be declaring class fields.

answered Feb 19, 2019 at 22:44

rayray's user avatar

rayrayrayray

1,5751 gold badge8 silver badges15 bronze badges

Typescript for Windows issue

This works in IE, chrome, FF

export const OTP_CLOSE = { 'outcomeCode': 'OTP_CLOSE' };

This works in chrome, FF, Does not work in IE 11

export const OTP_CLOSE = { outcomeCode: 'OTP_CLOSE' };

I guess it somehow related to Windows reserved wordsenter image description here

answered Nov 15, 2019 at 21:58

Lev Savranskiy's user avatar

Lev SavranskiyLev Savranskiy

4222 gold badges7 silver badges19 bronze badges

Приветствую!

При работе с WebBrowser возникли проблемы, при выполнении JS выдает ошибку, однако при открытии в Google Chrome никаких ошибок нет.

Код HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
<script src="circle.js" type="text/javascript"></script>
</head>
<body>
<div id="map" style="width:300px; height:300px"></div>
</body>
</html>

Код JS:

ymaps.ready(init);
function init() {
var myMap = new ymaps.Map("map", {
    center: [60.000000, 30.000000],
    zoom: 10
});
var myCircle = new ymaps.Circle([
    [60.000000, 30.000000],
    01000
], {
    balloonContent: "Радиус круга - 10 м",
}, {
    draggable: false,
    fillColor: "#DB709350",
    strokeColor: "#990066",
    strokeOpacity: 0.7,
    strokeWidth: 2
});
myMap.geoObjects.add(myCircle);
}

Оба кода взяты из песочницы яндекса, являются полностью рабочими. Помогите заставить WebBrowser работать как надо.
Укажите мне путь истинный.

пс: засунул в свой проект Awesomium, он ошибок не выдает но и не отображает ничего, но это думаю из за неправильной настройки, впервые им пользуюсь.

Новости по ошибке:

1 Для того что бы не было ошибок в выполнении JS, необходимо в html файл добавить код указывающий на контент, так как Default — ie6.
Код, который необходимо добавить:

<meta http-equiv="x-ua-compatible" content="ie=edge">

Однако это не решило всех проблем, теперь WebBrowser ведет себя как Awesomiun, все работает не выдает ошибок, но карту не отображает по каким то причинам.

2 Наконец таки карта отобразилась но не работают элементы(кнопки приблизить отдалить и тд), а так же не перетаскивается карта зажатием лкм, ее можно только масштабировать колесиком.

На чтение 4 мин. Опубликовано 15.12.2019

В старом блоге была заметка с точно таким же заголовком и аналогичной смысловой нагрузкой. Я подумал, что нет никакого резона переносить ее в новый блог, слишком уж сомнительной, как мне казалось, была ее ценность.

Тем не менее, время от времени натыкаюсь на скрипты, где расставлены все те же грабли. Ситуация приобретает особый шарм, если содержащее ошибку приложение пропущено через компрессор и несжатые исходники отсутствуют.

Ошибка: Error: Expected identifier, string or number

Данная ошибка возникает в том случае, если в перечислении свойств объекта присутствует лишняя запятая — после последнего свойства. JavaScript движок в IE 7 (и ниже) считает, что не задано наименование следующего свойства объекта. Ситуация усугубляется тем, что при возникновении такой ошибки прекращается обработка всех JS скриптов на странице.

Ошибку вызовет вот такой код:

Как показывает опыт, чаще всего она допускается при перечислении свойств плагинов популярных JavaScript фреймворков. В предыдущей заметке я приводил пример, в котором фигурирует jQuery:

В обоих примерах, если убрать последнюю запятую в списке свойств, ошибка «Expected identifier, string or number» исчезнет.

Рассмотрим код в котором возникает ошибка. Причём ошибка только в браузере IE (у меня IE8), в остальных браузерах с этим нормально.

Это первый случай ошибки, который много где уже описан. Когда заканчивается перечисление переменных, то после последнего элемента не нужно ставить запятую. Internet Explorer считает это ошибкой и вообще не будет выполнять весь код, не откроет сайт (календарь FullCalendar в моём случае).

Но даже удалив запятую, ошибка не исчезнет. Именно этот случай у меня и возник (запятую ткнул для общности решения проблемы). При просмотре текста ошибки:

Error: Предполагается наличие идентификатора, строки или числа ( Expected identifier, string or number” )

Оказывается в браузере Internet Explorer слово delete — зарезервированное слово и просто так вводить переменную delete нельзя. Решение проблемы: заключить в одинарные кавычки, вот так — ‘delete’.

Правильный код, который будет работать в IE:

Using the word class as a key in a Javascript dictionary can also trigger the dreaded «Expected identifier, string or number» error because class is a reserved keyword in Internet Explorer.

When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.

Hope this hint saves you a day of debugging hell.

А здесь можно видеть список зарезервированных слов, чтобы уже не натыкаться (как видим save и close сюда не входят, поэтому их можем не брать в кавычки).

Список зарезервированных переменных для JavaScript, избегайте называть переменные зарезервированными словами!

abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
catch final native throws
char finally new transient
class float null true
const for package try
continue function private typeof
debugger goto protected var
default if public void
delete implements return volatile
do import short while
double in static with

almix
Разработчик Loco, автор статей по веб-разработке на Yii, CodeIgniter, MODx и прочих инструментах. Создатель Team Sense.

I have an object like;

and when i run my page in IE8 standards its giving me the following error;

SCRIPT1028: Expected identifier, string or number

and points to the line : class:’ ‘,

can anyone please tell me why i cant use this for IE? is it a reserved word or something?

4 Answers 4

You need to add quotes round the class which is a reserved word. Please also note, that you should remove the last comma:

  • Ошибка правого колеса пылесоса xiaomi mi robot vacuum mop essential
  • Ошибка предполагается наличие идентификатора код 800a03f2
  • Ошибка правило пример работа над ошибками
  • Ошибка предохранителя cru scx 4321
  • Ошибка прав записи фотошоп