Javascript array reverse function unexpected behavior

后端 未结 8 2119
执念已碎
执念已碎 2021-01-03 05:10

I would like to understand why situation 1 and situation 2 don\'t return the same results.

Situation 1 :

var array1 = [\"1\", \"2\", \"3\"];
var arra         


        
8条回答
  •  清歌不尽
    2021-01-03 05:54

    In Situation 1

    The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

    In Situation 2 you have the same reference. You are printing array1 array before reverse it.

    var array1 = ["1", "2", "3"];
    var array2 = array1;
    
    console.log(array1);           // [ '1', '2', '3' ]
    console.log(array2.reverse()); // [ '3', '2', '1' ]
    console.log(array1);           // [ '3', '2', '1' ]
    

提交回复
热议问题