Javascript Data Type How to - Modify array prototype








Question

We would like to know how to modify array prototype.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from ww  w  . j av  a  2  s.co m-->
Object.defineProperty(Array.prototype, 'x', {
    enumerable: false,
    value: 10
});
var a = ['first', 'second', 'third'],
    s = '';
for (var i in a) {
    s += '<br/>a[' + i + '] = ' + a[i];
}
document.writeln( s + '<br/>a.x=' + a.x);

</script>
</head>
<body>
  <p id="res"></p>
</body>
</html>

The code above is rendered as follows: