Jump to content

Array problem


Zerivo

Recommended Posts

Hello i try make it like:

<html><head> <script type="text/javascript">
function Code()
{
A=["T1","T2","T3",4,2,1];
var B1=A;var B2=A;var B3=A;
if (A[0]=="T2") {B1[3]=5;}
if (A[1]=="T2") {B2[3]=5;}
if (A[2]=="T2") {B3[3]=5;}
document.getElementById('W1').innerHTML="B1:"+B1[3]
document.getElementById('W2').innerHTML="B2:"+B2[3];
document.getElementById('W3').innerHTML="B3:"+B3[3];
}
</script></head><body>
<input type="button" value="Code it!" onClick="Code()"><br><br><br>
<div id="W1"></div>
<div id="W2"></div>
<div id="W3"></div>
</body>
when i press button then i got 5 on all B1, B2 and B3. but it should be only B2 have 5 while other got 4.
Why it going wrong?
Link to comment
Share on other sites

if i charge it from.
var B1=A;var B2=A;var B3=A;
if (A[0]=="T2") {B1[3]=5;}
if (A[1]=="T2") {B2[3]=5;}
if (A[2]=="T2") {B3[3]=5;}
document.getElementById('W1').innerHTML="B1:"+B1[3];
document.getElementById('W2').innerHTML="B2:"+B2[3];
document.getElementById('W3').innerHTML="B3:"+B3[3];
to (those text with bold are charge)
var B1=A[3];var B2=A[3];var B3=A[3];
if (A[0]=="T2") {B1=5;}
if (A[1]=="T2") {B2=5;}
if (A[2]=="T2") {B3=5;}
document.getElementById('W1').innerHTML="B1:"+B1;
document.getElementById('W2').innerHTML="B2:"+B2;
document.getElementById('W3').innerHTML="B3:"+B3;
so it work fint, it got 5 on B2 while other got 4. but i want charge other number in array too
like:
if (A[0]=="T2") {B1[3]=5;}
if (A[0]=="T2") {B1[4]=2;}
if (A[0]=="T2") {B1[5]=5;} etc
so it save me lots time but it don't work well
Edited by Zerivo
Link to comment
Share on other sites

Use for loop to loop through array values, and if condition, and make change if match

for(i=0; i< A.length; i++){if(a[i]==="T2"){a[i]=5;}}

you can then put it in a function

function ChangeArrayValue(valueToMatch, valueToChangeTo){for(i=0; i< A.length; i++){if(a[i]===valueToMatch){a[i]=valueToChangeTo;}}}

and call it with

 

ChangeArrayValue('T2', 5);
Edited by dsonesuk
Link to comment
Share on other sites

Javascript uses references for non-primitive datatypes. when you had B1=A and B2 =A they both "point" to the same memory location of A. Javascript wants to save memory any chance it can so it uses direct references to avoid eating up memory for identical memory values. In order to copy the entire array to a new variable you'll need to manually walk through all its elements and assign them on by one, as dsonesuk demonstrates.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...