troubleshooting Question

Why is my local Javascript array's being modified in external functions?

Avatar of Charlie_S24
Charlie_S24 asked on
Scripting Languages
1 Comment1 Solution338 ViewsLast Modified:
Although I thought I understood how local and public variables work with JavaScript, I still have a function modifying my two-dimensional array.  I'm not sure how to prevent that from happening.  (Have I declared the array properly?  Am I passing it properly?)

My goal is to have a two-dimensional array in the main routine whose data is passed to a function that uses the data, but leaves the original array in the main routine untouched.

Below is a little bit of fictitious code that duplicates the problem.  

Your help would be appreciated.

<html>
<body>
 
<p id="demo">Click the button to test code.</p>
 
<button onclick="myFunction()">Try it</button>
 
<script type="text/javascript">

function myFunction()
{
  var aryFirstArray =  new Array(1)
  aryFirstArray[0] = new Array()
  aryFirstArray[0][0] = "I am expecting the 2nd dimension to still be 5: "
  aryFirstArray[0][1] = 5
  myOtherFunction(aryFirstArray)
 
  var x=document.getElementById("demo");
  x.innerHTML=aryFirstArray;
}
function myOtherFunction(aryDifferentArray)
{
  aryDifferentArray[0][1] = 4
}
</script>
</body>
</html>
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 1 Comment.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros