Arrays Stored By Address

[Total: 0    Average: 0/5]

Data is stored at memory locations. When the data in a varible (say x=1) the value (1 in this case) is stored into memory directly. This is Store-By-Value.

Body Code:

Three examples are shown.<BR>
<li>1) Normal values are stored in memory.
Copy from one into another the value is copied.
<script type=text/javascript>
var a=1
var b=a
a=2
document.write('<div class=code>var a=1<br>var b=a<br>a=2 <br></div>')
document.write('<BR><div class=desc>Lets see what happened to "a" and "b"</div>')
document.write('<br><span class=desc>a = </span><span class=result>'+a+'</span><br><span class=desc>b = </span><span class=result>'+b+'</span>')
document.writeln("<BR><HR>")
</script>
<div class=desc>
<li>2) An array stores values by address. Copy into another array - just the
   address of the data store is copied over.  Modify the contents and the
   address doesn't change so both variables point to the modified data.
</div>
<script type=text/javascript>
var c = [1,2,3]
var d = c
c[0] = 4
document.write('<div class=code>var c=[1,2,3]<br>var d=c<br>c[0]=4</div>')
document.write('<BR><div class=desc>Lets see what happened to "c" and "d"</div>')
document.writeln('<br><span class=desc>d = </span><span class=result>'+d+'</span><br><span class=desc>c = </span><span class=result>'+c+'</span>');
document.writeln("<BR><HR>")
</script>
<div class=desc>
<li>3) However if the original array is "created" with a "new" or equal syntax. The copy still points to
   the original, but the "new created one" has new memory allocated to it.
</div>
<script type=text/javascript>
var e = [1,2,3]
var f = e
e[1]="OLD"
e = [4,5,6]
e[1]="NEW"
document.write('<div class=code>var e=[1,2,3]<br>var f=e<br>e[1]="OLD"<br>e=[4,5,6]<br>e[1]="NEW"</div>')
document.write('<BR><div class=desc>Lets see what happened to "e" and "f"</div>')
document.writeln('<br><span class=desc>f = </span><span class=result>'+f+'</span><span class=desc><br>e = </span><span class=result>'+e+'</span>');
</script>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *