Javascript Data Type How to - Set the value into an array from a function








Question

We would like to know how to set the value into an array from a function.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w  w w .  j  ava2s  .  com-->
function Foo(arr) {
    this.arr = arr;
}
var f = new Foo(['a', 'b', 'c']);
Foo.prototype.setv = function(index, v) {
    this.arr[index] = v;
}
idx = 0;
f.setv(idx, "Z");
document.writeln(JSON.stringify(f));
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: