Javascript Data Type How to - Get array element index








Question

We would like to know how to get array element index.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from ww  w .ja v  a 2s.  c  om-->
    var obj = {arr: [{x: 1, y: 2},{x: 3, y: 4},{x: 5, y: 6}]};
    function myFunction(myObj)
    {
        document.writeln(obj.arr.indexOf(myObj)); // 2
    }
    myFunction(obj.arr[2]);
}
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: