lundi 3 décembre 2018

change of array value change the previous clone of this array

Function f3 accepts an array of simple objects, a, as parameter and returns an array whose items are copies of the items of array a

why when i do this statement b[0].a = 2; the value of a[0].a; change to

this is my code

<script type="text/javascript">
    function f3(obj= [{a: 1, b: 'str'}]) {
        let r = [];
        for (let prop of Object.values(obj)){
            r.push(prop);
        }
        return(r);
    }


    const a = [{a: 1, b: 'str'}];
    console.log(a[0]);// output {a: 1, b: "str"}

    const b = f3(a); 
    console.log(b[0]);// output {a: 1, b: "str"}
    console.log(b[0].a);// output 1 

    b[0].a = 2;

    console.log(a[0]);// output {a: 2, b: "str"}
    console.log(b[0]);// output {a: 2, b: "str"}
    console.log(a[0].a);// output 2
    console.log(b[0].a);// output 2

</script>




Aucun commentaire:

Enregistrer un commentaire