Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not-well formed error in for loop

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.

like image 298
Instance Hunter Avatar asked Nov 03 '09 23:11

Instance Hunter


2 Answers

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 &amp;. I do not recommend this option; it'll make your code unreadable and will almost definitely not work in IE.

like image 61
SLaks Avatar answered Sep 30 '22 19:09

SLaks


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.

like image 22
Sukasa Avatar answered Sep 30 '22 19:09

Sukasa