Javascript array reverse function unexpected behavior

后端 未结 8 1880
执念已碎
执念已碎 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:11

    The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. Thus, it does not return the reversed array.

    CHECK the manuel. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

    0 讨论(0)
  • 2021-01-03 06:14

    It's important to note that Array.reverse() does two things:

    • It mutates the array it's given by reversing it
    • It returns a reference to the array that was just reversed

    Let's take a look at your examples and what's going on/

    Situation One

    var array1 = ["1", "2", "3"];  // Creates new array
    var array2 = array1.reverse(); // Reverse array1 and stores reference to array1 in array2
    
    // Since array1 and array2 point to the same object, they will have
    // the same values since they are pointing to the same object
    console.log(array1); // ["3", "2", "1"]
    console.log(array2); // ["3", "2", "1"]
    

    Situation Two

    var array1 = ["1", "2", "3"];  // Creates new array
    var array2 = array1;           // array2 now holds a reference to array1
    
    // Same as the previous example, array1 and array2 both have the
    // same values since they are pointing to the same object    
    console.log(array1);           // ["1", "2", "3"]
    
    // Now we reverse array2, which reverses array1 AND array2
    console.log(array2.reverse()); // ["3", "2", "1"]
    
    // array1 is now also reversed
    console.log(array1);           // ["3", "2", "1"]
    

    In the second situation, after you call array2.reverse(), both array1 and array2 become reversed since they're pointing to the same object reference.

    0 讨论(0)
提交回复
热议问题