views:

532

answers:

4

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.

+1  A: 

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.

Sukasa
There is no HTML or other Javascript.
Daniel Straight
A: 

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.

Matthew Flaschen
That IS the full file, aside from various combinations of html and script tags. I've tried with just a script tag. I've tried with a full HTML page including just a script tag in the body, with and without a doctype.
Daniel Straight
+7  A: 

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.

SLaks
Awesome. Thanks.
Daniel Straight
I thought I had tried the DOCTYPE too, but I guess not.
Daniel Straight
A: 

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>
James Bailey