iLevi
iLevi

Reputation: 936

Problem to extend array

i have a problem. I have written a code for extend Array Element, and works fine, but when i iterate over array this show extended functions. I don't know how stop this. There is the code...

Array.prototype.remove  = function(e)   {var i = this.inArray(e);if(i != -1) this.splice(i, 1);return this;};
Array.prototype.add     = function(e)   {this.push(e); return e;};
Array.prototype.inArray = function(v)   {for(i in this) if(v==this[i])return i;return false;};
Array.prototype.toggle  = function(v)   {this.inArray(v) ? this.remove(v) : this.add(v);return this;};

So when i tried this...

var arr = [1,2,3,4,5];
for(i in arr)
document.write(arr[i]);

this print array values and functions extended. somebody can help me? I can't change the code "for(x in y)" because is many times in many files.

Upvotes: 3

Views: 221

Answers (4)

kennebec
kennebec

Reputation: 104850

Iterate through the array's indexes.-

var A=[1,2,3,4,5];

Array.peototype.omega=function(replacer){
  var L= this.length;
  if(L)--L;
  if(replacer!=undefined)this[L]=replacer;
  return this[L]
}

for(var i=0,L=A.length; i<L; i++){
//do something to A[i]
}

Upvotes: 0

sciritai
sciritai

Reputation: 3748

Couple of things to read that will explain the situation

https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Use .forEach() when iterating over an array. It's pretty well supported, including Mobile Safari and Android, https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach

Upvotes: 2

alex
alex

Reputation: 490657

If you must modify the Array prototype, you must use hasOwnProperty() otherwise it will pick up properties up the prototype chain.

var arr = [1,2,3,4,5];
for(var i in arr) {
    if (arr.hasOwnProperty(i)) {
        document.write(arr[i])
    }
}

You said, however, you don't want to change your for (in) loops. Why don't you have an Array utility object? Or just use normal for loops? These are Arrays right? for (in) is for iterating over Object properties.

Upvotes: 1

cdhowie
cdhowie

Reputation: 169478

for ... in loops through object properties in JavaScript, not array elements. The for ... in loops are simply the wrong way to do this. You've said that you can't change them, but using this syntax to enumerate the contents of arrays is not a recommended practice in JavaScript, for the reason you have just discovered.

You are going to have to rewrite the for ... in loops sooner or later.

Upvotes: 0

Related Questions