Javascript Array Extension

Just wondering. I extended the JavaScript array object with my prototype as follows:

<html>
<head>
</head>
<body>
<script type="text/javascript">
  function SomeMethod(){
  alert('Hello');
  }
  if(typeof Array.prototype.SomeMethod ==='undefined' ){
    Array.prototype.SomeMethod = SomeMethod;
  }
  var ax=new Array("A","B","C");
  for(var i in ax){
    document.write(ax[i]);
  }
</script>

</body>
</html>

The result will be:

ABCfunction SomeMethod() { alert("Hello"); } 

EDIT: Although I already found the answer, I feel the need to add some more information, so for others it would be clearer.

0
source share
3 answers

for..inIterates over the (non-built-in) properties of an object. Do not use it to iterate over an array. Just use a regular loop for.

Read this link https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in#Description

+3
source

The question will be helpful; -)

, , ? JS "DontEnum" , , , :

for(var i in ax) {
    if (a.hasOwnProperty(i)) {
        document.write(ax[i]);
    }
}

for...in , .

+2

. , , -.

:

JavaScript Hashtables.

var myHashtable = {};

- . JavaScript , . , -.

myHashtable["name"] = "Carl Hollywood";

, .

myHashtable.city = "Anytown";

, . - , .

, JavaScript - Java . JavaScript : - ,

var myHashtable = new Object();

.

There is a possibility of enumeration built into the for statement.

for (var n in myHashtable) {
    if (myHashtable.hasOwnProperty(n)) {
        document.writeln("<p>" + n + ": " + myHashtable[n] + "</p>");
    }
}

I believe jquery.each code does this for you, but I'm not 100% sure.

If you use the actual array and want to use it correctly, you should simply do

for (var i = 0; i < myArray.length; i++)
{
    alert(myArray[i]);
}
+1
source

All Articles