Javascript Array Reverse

How does Javascript array.reverse() ? Does it go through and replace every element of the array? If so, is it necessary to take an O (n) array of size n?

I think the reason I'm asking for is because I was wondering if array.reverse() the same as:

 for(var i = 0; i < a.length / 2; i++) { var holder = a[i]; a[i] = a[a.length - 1 - i]; a[a.length - 1 - i] = holder; } 

NOTE : Sorry if the Javascript code I posted is incorrect, it is now quite late.

EDIT : Fixed a.length - a.length / 2 .

+7
source share
2 answers

For more details on how this works, read the corresponding section of the specification . Here's the algorithm:

  • Let O be the result of calling ToObject, passing this value as an argument.

    1. Let lenVal be the result of calling the O [[Get]] internal method with the argument "length".
    2. Let len ​​- ToUint32 (lenVal).
    3. Let the middle floor (len / 2).
    4. Let less than 0.
    5. Repeat while the bottom is middle

      • Let the upper value be less than -1. A.
      • Let upperP be ToString (top).
      • Let lowerP be ToString (below).
      • Let lowerValue be the result of calling the [[Get]] O internal method with argument lowerP.
      • Let upperValue be the result of calling the [[Get]] O internal method with argument upperP.
      • Let lowerExists be the result of calling the O [[HasProperty]] internal method with argument lowerP.
      • Let upperExists be the result of calling the O [[HasProperty]] internal method with the argument upperP.
      • If lowerExists are true and upperExists are true, then

      • Call the internal method O [[Put]] with arguments lowerP, upperValue, and true.

      • Call the internal method O [[Put]] with arguments upperP, lowerValue, and true.
      • Else if lowerExists is false and upperExists is true then
      • Call the internal method O [[Put]] with arguments lowerP, upperValue, and true.
      • Call the internal method O [[Delete]] with arguments upperP and true.
      • Otherwise, if lowerExists is true and upperExists is false, then
      • Call the internal method O [[Delete]] with arguments lowerP and true.
      • Call the internal method O [[Put]] with arguments upperP, lowerValue, and true.
      • Otherwise, both lowerExists and upperExists are false
      • No action required.
      • Increase by 1.
    6. Refund O.
+6
source

The actual algorithm is almost the same as what you specified. Just change your for loop to iterate only to a.length/2 , and it will be similar to what Array.reverse will do. I will just skip the internal details for the sake of simplicity. So it will be

 for(var i = 0; i < a.length/2; i++) { var holder = a[i]; a[i] = a[a.length - 1 - i]; a[a.length - 1 - i] = holder; } 
+2
source

All Articles