Page 108 - JavaScript
P. 108

ending before the index specified:


         var array = [1, 2, 3, 4];
         array.splice(2);


        ...leaves array containing [1, 2] and returns [3, 4].


        Delete



        Use delete to remove item from array without changing the length of array:


         var array = [1, 2, 3, 4, 5];
         console.log(array.length); // 5
         delete array[2];
         console.log(array); // [1, 2, undefined, 4, 5]
         console.log(array.length); // 5


        Array.prototype.length



        Assigning value to length of array changes the length to given value. If new value is less than
        array length items will be removed from the end of value.


         array = [1, 2, 3, 4, 5];
         array.length = 2;
         console.log(array); // [1, 2]


        Reversing arrays


        .reverse is used to reverse the order of items inside an array.


        Example for .reverse:


         [1, 2, 3, 4].reverse();


        Results in:


         [4, 3, 2, 1]


              Note: Please note that .reverse(Array.prototype.reverse) will reverse the array in place.
              Instead of returning a reversed copy, it will return the same array, reversed.


               var arr1 = [11, 22, 33];
               var arr2 = arr1.reverse();
               console.log(arr2); // [33, 22, 11]
               console.log(arr1); // [33, 22, 11]


        You can also reverse an array 'deeply' by:





        https://riptutorial.com/                                                                               65
   103   104   105   106   107   108   109   110   111   112   113