D
Denis McMahon
I have functions that return first, last or list of array indexes where
the array value is x. An example:
<script type="text/javascript">
function arrayFirstIndexOf(x, a) { // find first x in array a
for (var i=0, l=a.length; i < l; ++i) if (a === x) return i;
return false;
}
</script">
I thought I'd try and add these as array methods using Array.prototype:
<script type="text/javascript">
Array.prototype.firstIndexOf = function(x) { // find first x in array
for (var i=0, l=this.length; i<l; ++i) if (this === x) return i;
return false;
};
</script>
The plan is that then, any array will have an Array.firstIndexOf(x)
method.
However, and I suspect this is a closure issue, I start getting
unexpected "undefined" results when I add the array prototype definition,
even when not actually calling it.
So, it's not only not doing what I want, but it's also doing something
else that breaks previously working code.
Then I tried this:
<script type="text/javascript">
function arrayFirstIndexOf(x) { // find first x in array
for (var i=0, l=this.length; i<l; ++i) if (this === x) return i;
return false;
}
Array.prototype.firstIndexOf = arrayFirstIndexOf;
</script>
and that didn't work either.
So I guess I'm missing something pretty fundamental either (a) relating
to "this" when using prototype, or (b) relating to closures, or (c) both.
But I can't for the life of me see what I'm missing.
Any non cryptic hints and / or pointers would be appreciated.
Rgds
Denis McMahon
the array value is x. An example:
<script type="text/javascript">
function arrayFirstIndexOf(x, a) { // find first x in array a
for (var i=0, l=a.length; i < l; ++i) if (a === x) return i;
return false;
}
</script">
I thought I'd try and add these as array methods using Array.prototype:
<script type="text/javascript">
Array.prototype.firstIndexOf = function(x) { // find first x in array
for (var i=0, l=this.length; i<l; ++i) if (this === x) return i;
return false;
};
</script>
The plan is that then, any array will have an Array.firstIndexOf(x)
method.
However, and I suspect this is a closure issue, I start getting
unexpected "undefined" results when I add the array prototype definition,
even when not actually calling it.
So, it's not only not doing what I want, but it's also doing something
else that breaks previously working code.
Then I tried this:
<script type="text/javascript">
function arrayFirstIndexOf(x) { // find first x in array
for (var i=0, l=this.length; i<l; ++i) if (this === x) return i;
return false;
}
Array.prototype.firstIndexOf = arrayFirstIndexOf;
</script>
and that didn't work either.
So I guess I'm missing something pretty fundamental either (a) relating
to "this" when using prototype, or (b) relating to closures, or (c) both.
But I can't for the life of me see what I'm missing.
Any non cryptic hints and / or pointers would be appreciated.
Rgds
Denis McMahon