What is the difference when a integer, string and array pass as function parameter in javascript

StackOverflow https://stackoverflow.com/questions/23221173

  •  07-07-2023
  •  | 
  •  

Domanda

As question, What is the difference when a integer, string and array pass as function parameter in javascript?

Below are my question:

<html>
    <head>
        <script>
            var a = 0;
            var b = new Array();
            b.push(0);

            function Add(num) {
                num++;
            }

            function Add1(num) {
                num[0]++;
            }

            Add(a);
            Add1(b);

            alert(a);
            alert(b[0]);
        </script>
    </head>

    <body></body>
</html>

And it ended up provide two different value, why? The first result 0 and the second one is 1

È stato utile?

Soluzione

Arrays as objects are passed in functions by reference while primitives (e.g. strings and numbers) are passed by value. Here is an example:

function test(arr, obj, prim) {
    arr[0]++;    // by reference
    obj.prop++;  // by reference
    prim++;      // by value

    return prim; // to get the amended primitive value back
}

var arr = [0],
    obj = { prop: 0 },
    prim = 0,
    result;

result = test(arr, obj, prim);

console.log(arr, obj, prim);  // [1], Object {prop: 1}, 0
console.log(result);          // 1

GOOD ARTICLE: http://snook.ca/archives/javascript/javascript_pass

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top