Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  171] [ 7]  / answers: 1 / hits: 21081  / 15 Years ago, fri, july 10, 2009, 12:00:00

So lets say I've added some prototype methods to the Array class:





Array.prototype.containsKey = function(obj) {
for(var key in this)
if (key == obj) return true;
return false;
}

Array.prototype.containsValue = function(obj) {
for(var key in this)
if (this[key] == obj) return true;
return false;
}



then I create an associative array and attempt to loop through it's keys:





var arr = new Array();
arr['One'] = 1;
arr['Two'] = 2;
arr['Three'] = 3;

for(var key in arr)
alert(key);



this returns five items:




-One
-Two
-Three
-containsKey
-containsValue


but I want (expect?) only three. Am I approaching this wrong? is there a way to hide the prototype methods? or should I be doing something differently?


More From » arrays

 Answers
5

You can use JavaScript's hasOwnProperty method to achieve this in the loop, like this:



for(var key in arr) {
if (arr.hasOwnProperty(key)) {
...
}
}


Reference: This YUI blog article.


[#99150] Tuesday, July 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;