Javascript not-well formed error in for loop - javascript

I copied this code from an example. I've read it 100 times.
Array.prototype.map = function(fn) {
var r = [];
var l = this.length;
for(var i = 0; i < l; i++) {
r.push(fn(this[i]));
}
return r;
};
Why does Firefox say:
not well-formed
file:///some/path.html Line: 5
for(var i = 0; i < l; i++) {
-------------------^
UPDATE
The error is only shown when Firebug is turned on for the page.

You are using Javascript code in an HTML page claiming to be fully XHTML-compliant. Therefore, the < character cannot appear in the Javascript, as it would be interpreted as the beginning of an XHTML tag.
There are a number of ways to fix this.
You could change the DOCTYPE and make it not XHTML.
You could enclose the Javascript in a <![CDATA[ section.
You could move the Javascript into a separate .js file.
You could escape every occurrence of < with &lt and every & with &. I do not recommend this option; it'll make your code unreadable and will almost definitely not work in IE.

Likely your error isn't in this code, but something above it trickling errors down. So, instead of finding an error in this code, look above for malformed HTML or javascript that could be causing this error instead.

If I use the following HTML and your text as "test.js", I too get no errors in Firebug.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
test
</body>
</html>

Works for me. Please post the full file, and make sure you are using script tags.
I posted a validating pastebin file (Chetan's was technically not valid), and it works fine with Firebug. So I suggest you come back with a full page of validating code that doesn't work.

Related

Getting "Uncaught SyntaxError: Unexpected token ;" error while using for loop

Here I have a loop to iterator over html elements in a JSF application.
var tmp = document.getElementsByTagName("input");
var counter = 0;
var arr = new Array();
for (var i = 0; i<tmp.length; i++) {
if (tmp[i].parentNode.nodeName === "TD" && tmp[i].getAttribute("type") !== "submit") {
arr[counter] = tmp[i];
counter++;
}
}
This loop is inside this script tag:
<script type="text/javascript">
<!--
//-->
</script>
When I load the page in the web browser I get following error(shown in google chrome developer tools)
As you can see in your screenshot, your script in the HTML page has < where it should have <. This is your syntax error. Are you generating this page with some templating language that "escapes" HTML code? That would cause this problem.
One good solution is to put your JavaScript code in a separate .js file. That should avoid the escaping and leave your code unchanged.
If you do need to have inline JavaScript right there in the HTML page, most templating languages have a way to turn off escaping for a specific piece of text.
The line in picture 2 isn't the same as the one in picture 1. < was substituted for <, which is the HTML escape code for <. The error subsequently does not lie within your code itself, but somewhere in your development workflow. You either saved the file with the wrong contents (which I presume to be unlikely) or your web server or any pre processor is messing up by HTML escaping code inside script-tags.

Markup Validation error in Javascript

I am getting this error in my markup validation:
Warning Line 23, Column 23: character "<" is the first character of a delimiter but occurred as data
for (var i = 0; i < array.length; i++) {
Is there something wrong with the "<" character in the following js?
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.src = array[i];
preloadImages.list.push(img);
}
}
It looks like your document is XHTML and your Javascript is inlined. At least you seem to be validating against XHTML. Since XHTML is rather strict and closer to XML, < is interpreted as the start of a new tag and confused the validator.
There is a number of ways to fix this:
Use HTML5 instead of XHTML; really, this usually is the best choice unless you have a good reason to stick to XHTML. It is understood by all major browsers and is the latest and most modern doctype that allows all the cool new features of the Web 2.0. The doctype for HTML5 looks like this:
<!DOCTYPE html>
<html>
....
Don't inline your Javascript, but add it as an external resource. You should be doing this all the time anyway, no matter what doctype you are using:
<script type="text/javascript" src="yourScript.js"></script>
Enclose the script in a CDATA block:
<script type="text/javascript">
<![CDATA[
// your code
]]>
</script>
You can read up on doctypes and XHTML for further details.

Prettify fails to handle less-than in certain circumstances

If I try the following test case with prettify, if doesn't work correctly.
<!DOCTYPE html>
<head><script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script></head>
<body>
<pre class="prettyprint lang-java">
for(int i = 0; i <things.length; i++)
</pre>
</body></html>
The output reads "for(int i = 0; i " which suggests it failed to handle the less-than correctly.
I have submitted a bug to the project, but I wonder if there is a workaround I can use in the meantime?
It's possible to workaround this by tweaking the input source code, e.g. changing it to "for(int i =0; i < things.length; i++)" (adding a space after the less-than). However, I can't rely on doing this, as my tool runs unattended on client sites. However, I'd be happy to hack at Prettify, or run the source code through some kind of pre-filter.
Recommendations on alternatives to prettify are welcome.
Literal < and > characters in HTML documents should be encoded as entities, so it should be:
<pre class="prettyprint lang-java">
for(int i = 0; i < things.length; i++)
</pre>

Uncaught Reference Error:_______ is not defined

I'm a beginner with limited knowledge of both Javascript and html, sorry if my questions are very basic.
I'm trying to write a basic webpage that will do something to an array using Javascript when a button is clicked, then print the result to the page.
<!DOCTYPE html>
//error here
<html>
<head>
<title>Thursday's Homework</title>
<script>
var problem1 = function()
{for (var i = 0; i <= 50; i += 5) {
document.write(i + " ");
}
}
var myArray = []
var problem2 = function()
{for (var i = 0; i <= 9; ++i){
myArray[i]
}
document.write(myArray)
</script>
</head>
<body>
<center><h2><b> My Homework for Thursday<b></h2></center>
<p>This is my code for Problem 1:</p>
<input type="button" onclick = "problem1()" value="Does it work?">
//error here
<p>This is my code for Problem 2:</p>
<input type="button" onclick = "problem2()" value="Does it work?">
//error here
</body>
</html>
I'm getting three error messages when I debug in Chrome using developer tools:
After line 1: Uncaught SyntaxError: Unexpected end of input
After line 22(the first button): Uncaught ReferenceError: problem1 is not defined
After line 24(the second button): Uncaught Reference Error: problem2 is not defined
I'm also wondering if there's a better way to display the outputs than document.write because that makes it so that the page needs to be reloaded each time to see the next result.
I'm new, so my apologies if this is completely the wrong way to create this whole thing. If that's the case, just point me in the right direction.
UPDATE:
I've fixed the syntax errors and it's running fine. I'm still wondering about a better way to display my result that document.write. I'm not too knowledgeable, so if you have a suggestion, could you give me an idea of how to implement it?
You are missing a closing } after problem2.
That is the most common cause for this kind of error. The JS interpreter breaks since the function body is not properly closed, stops parsing. Then something else tries to reference a variable/function that failed to get parsed and triggers the Reference Error.
I can see a few issues.
You are missing a closing } after problem2.
You have spaces around your = for onclick =.
You're not actually doing anything with myArray. That does not seem intentional.
Your code formatting is unclear and that can lead to difficulties later (and I think this, in part, caused the bug). Unless you have a particularly good reason you should avoid things like {for. Instead add a newline after the {.
close the brace of problem2();
instead of document.write(); u can specify a id like
or
and in the js use
document.getElementById("abc").innerHTML=i+" ";
for better and safer coding use jsLint ..
As for you second question, you can find a lot of helpful extensions for both Chrome and Firefox that can satisfy you for debugging.
Chrome has internal tools such as "Web Console" that allow you to watch variables for exemple.

javascript validation error

here's my code, which says error when i run it through w3.validator.org.
for (var i = 0; i < CheckBox.length; i++)
error message -
character "<" is the first character of a delimiter but occurred as data
how do i fix this?
If you are "using" XHTML then you need to wrap the code in CDATA:
<script type="text/javascript">
//<![CDATA[
// rest of your javascript goes here
//]]>
</script>
Is your input XHTML? If so, to validate it as XML you would need a CDATA block to contain your javascript code.

Categories