Page 113 - JavaScript
P. 113

clone3 = [...arrayToClone] // the shortest way


        5.1


         arrayToClone = [1, 2, 3, 4, 5];
         clone1 = Array.prototype.slice.call(arrayToClone);
         clone2 = [].slice.call(arrayToClone);


        Searching an Array


        The recommended way (Since ES5) is to use Array.prototype.find:


         let people = [
           { name: "bob" },
           { name: "john" }
         ];

         let bob = people.find(person => person.name === "bob");

         // Or, more verbose
         let bob = people.find(function(person) {
           return person.name === "bob";
         });


        In any version of JavaScript, a standard for loop can be used as well:


         for (var i = 0; i < people.length; i++) {
           if (people[i].name === "bob") {
             break; // we found bob
           }
         }



        FindIndex


        The findIndex() method returns an index in the array, if an element in the array satisfies the
        provided testing function. Otherwise -1 is returned.


         array = [
           { value: 1 },
           { value: 2 },
           { value: 3 },
           { value: 4 },
           { value: 5 }
         ];
         var index = array.findIndex(item => item.value === 3); // 2
         var index = array.findIndex(item => item.value === 12); // -1



        Removing/Adding elements using splice()


        The splice()method can be used to remove elements from an array. In this example, we remove
        the first 3 from the array.




        https://riptutorial.com/                                                                               70
   108   109   110   111   112   113   114   115   116   117   118