質問

Why the two scripts behave differently? I want the to use the first script, but in the second drawData() call it changes data; it's weird and not what I want to happen. The second script does not have this problem. Why is it like that, and how can I fix the first script?

First script does not change data:

    var data = ["right"];

    function drawData(arrs, type) {
        if (type == "percentage") {
            arrs[0] = "omg";
        }
        console.log(data[0]); // Changed!?
    }
    drawData(data);
    drawData(data, "percentage");

Second script:

    var data = "right";

    function drawData(arrs, type) {
        if (type == "percentage") {
            arrs = "omg";
        }
        console.log(data); // OK, not changed.
    }
    drawData(data);
    drawData(data, "percentage");

正しい解決策はありません

他のヒント

This is the difference between assignment to a local variable and mutation of the given object.

In both pieces of code arrs is a local variable, distinct from data. But the elements and other properties of arrs are exactly the same as those of data. Making changes to those property values (which is commonly called mutation of the object/array) will be visible whether you access them via arrs or via data. And this is exactly what the first script does.

The second script however, does not change a property value of arrs, but assigns an entirely new value to arrs, so that now it does not share any properties any more with data. This is even more apparent, because both data and arrs are primitive values which cannot mutate like explained in the previous paragraph. But even if they were objects or arrays, and you would do the following assignment:

arrs = [1234];

It would not affect data. data would only be affected if you would assign to a property/index of arrs without assigning to arrs directly.

First variant modifies object passed as parameter to function (which happens to be array) - so this change is seen outside function. Second variant assigns new value to function parameter (which happens to be reference to array) but does not change array itself.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top