Changing an array in a JavaScript function changes an array outside of a function?

why are two scenarios different? what I want is the first script, but in the second drawData () it modifies the data, this is strange. can someone tell me why this is so and how to fix it. thank!

    var data =           ["right"]  ;

function drawData(arrs,type){
    if(type=="percentage"){
        arrs[0]="omg";
    }
    alert(data[0]);

}
drawData(data);
drawData(data,"percentage");

second:

    var data =           "right"  ;

function drawData(arrs,type){
    if(type=="percentage"){
        arrs="omg";
    }
    alert(data);

}
drawData(data);
drawData(data,"percentage");
+5
source share
1 answer

The first option modifies the object passed as a parameter to the function (which is an array), so this change is considered outside the function. The second option assigns a new value to the function parameter (which is a reference to the array), but does not change the array itself.

0
source

All Articles