Javascript array reverse function unexpected behavior

后端 未结 8 2123
执念已碎
执念已碎 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 06:07

    The problem is that reverse() change the array itself. That means, if you write var array2 = array1.reverse() then array1 is reversed. Array1 contains now the reversed entries and on the other side array2 is initialized with this reversed array. Therefor you have the same output.

    On the second example with var array2 = array1 you have two variable referencing the same array. First you print out array1 which result in normal order. As second step you reverse array2 and print it out. The order has changed now. But if you print out array1 again now, the result will be the array in reversed order, because array1 and array2 refer to the same array.

提交回复
热议问题