Page 99 - JavaScript
P. 99

Use Array.prototype.slice like so:


         var arrayLike = {
           0: 'Value 0',
           1: 'Value 1',
           length: 2
         };
         var realArray = Array.prototype.slice.call(arrayLike);
         realArray = [].slice.call(arrayLike); // Shorter version

         realArray.indexOf('Value 1'); // Wow! this works


        You can also use Function.prototype.call to call Array.prototype methods on Array-like objects
        directly, without converting them:


        5.1


         var domList = document.querySelectorAll('#myDropdown option');

         domList.forEach(function() {
           // Do stuff
         }); // Error! forEach is not defined.

         Array.prototype.forEach.call(domList, function() {
           // Do stuff
         }); // Wow! this works


        You can also use [].method.bind( arrayLikeObject ) to borrow array methods and glom them on to
        your object:

        5.1


         var arrayLike = {
           0: 'Value 0',
           1: 'Value 1',
           length: 2
         };

         arrayLike.forEach(function() {
           // Do stuff
         }); // Error! forEach is not defined.

         [].forEach.bind(arrayLike)(function(val){
           // Do stuff with val
         }); // Wow! this works


        Modifying Items During Conversion


        In ES6, while using Array.from, we can specify a map function that returns a mapped value for the
        new array being created.

        6


         Array.from(domList, element => element.tagName); // Creates an array of tagName's




        https://riptutorial.com/                                                                               56
   94   95   96   97   98   99   100   101   102   103   104