Copy-by-value and reference-by-value in JavaScript

Copy pass by value and reference pass by value

Copy pass by value: The basic data types are all "copy pass by value".

  • #Copying by value means "copying" the value of one variable and passing it to another variable.

  • After copying and passing the value, there is no connection between the two variables. If the value of one variable is modified, the other will not change.

  • These two variables are independent of each other and have no connection.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>
        <script>
            var a=10;
            var b=a;
            a++;
            document.write("a的值为:"+a+"<br/>");
            document.write("b的值为:"+b);
        </script>
    </head>
    <body>
    </body>
</html>



##Pass-by-reference address: Composite data types are all "pass-by-reference address"

Pass-by-reference address: "Copy" the data address of a variable , passed to another variable. These two variables point to the "same address".

Everyone shares the same data.

If the value of one variable changes, then the value of the other variable must also change. We must change together.

Therefore, these two variables are related, and they need to be changed together.


<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>
        <script>
            var arr1=[10,20,30,40];
            var arr2=arr1;
            arr1[1]=100;
            document.write("arr1[1]的值为:"+arr1[1]+"<br/>");
            document.write("arr2[1]的值为:"+arr2[1]);
        </script>
    </head>
    <body>
    </body>
</html>



Continuing Learning
||
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> var a=10; var b=a; a++; document.write("a的值为:"+a+"<br/>"); document.write("b的值为:"+b); </script> </head> <body> </body> </html>
submitReset Code