开发者

Problem to extend array

开发者 https://www.devze.com 2023-03-28 12:49 出处:网络
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.

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.


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


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.


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.


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]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消