I'm getting a very strange response to a JS script I'm writing. I'm a bit new to JS, so I don't know much about altering existing classes (in this case, Arrays).
I hope I'm doing this properly, but here's a JSFiddles of the code I'm trying to run (abstracted significantly, but I believe I've included all the relevant parts)
I think the issue is that I don't know how to correctly alter the Array class, as, when I remove the "remove" alteration of Array.prototype, I get a different error (that Arrays don't have a remove function).
The Exception I'm getting is as follows:
`Uncaught TypeError: Object function (from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
} has no method 'shift'`
3 Answers 3
When you are looping through the members of strokes, you are getting the keys 0, 1 and "remove". When you use the third key you get strokes["remove"] (which is the same as strokes.remove), which will return the remove method that you added to the array prototype, and you get that error.
Loop through the indices of the array instead of the members of the array:
for (var i = 0; i < strokes.length; i++) {
strokes[i].shift(.05);
}
Comments
in for (sn in strokes), you get error when sn assign to 'remove', the value of strokes[sn] is the function you add to Array instead of stroke instance.
Change to
for (var i = 0; i < strokes.length; i++) {
strokes[i].shift(.05);
}
or test type first
if (typeof strokes[sn] != 'function') {
...
}
2 Comments
Try this:
for (var i = 0; i < strokes.length; i++) {
strokes[i].shift(.05); //Where I'm getting the error
}
jsFiddle: http://jsfiddle.net/UMHn5/2/
You have not included prototype in fiddle.
removeto arrays. There is alreadysplice. Anyway, you omitted the part where this method is called. Also,for (var key in object)is the wrong way to iterate over arrays. Use numericalfor.snis not aStrokeobject.hasOwnPropertyof the key.