当前位置:网站首页>Relevant methods of sorting arrays in JS (if you want to understand arrays, it's enough to read this article)

Relevant methods of sorting arrays in JS (if you want to understand arrays, it's enough to read this article)

2022-07-07 23:59:00 Xiao Zhang, run quickly.

         Our front-end programmers are working , In addition to enjoying what you write every day “ Beautiful pages and code groups ” outside , What we contact most in our work is Array .

         So why do you say that : We can think of , All the data on our page 、 picture , Words etc. , We can't always maintain a state , Then this page is very limited for our later use , You could even say , This page is unusable . What we need Data can change in real time 、 to update .

         So here comes the question , The amount of data we need for a page is very huge , How do we save and use our data ? Now , Our array appears . In the process of getting work , We can find out , The data returned by the backend , More or less Array type data , Then we must master how to use this array , Get the data we need from your array .

One 、 The concept of array

         An array is a collection of data , Each of these data is called an element . In the array , You can store any type of element . Arrays are an elegant way to store a set of data under a single variable name .

Two 、 Array creation

        JS There are two ways to create arrays provided in : Literal creation and Built in function creation

        2、1 Create an array of literals

var arr=[];// Create an empty array 
var arr1=[1,2,3,4,'red',true];// Each element in the array should use “ comma ” separate 

         2、2 utilize new Create an array by creating a built-in function

var arr = new Array();// Create a new array 

Be careful :Array()  A Use capital letters  

3、 ... and 、 Number to get array elements

        Index of array

                Indexes ( Subscript ): The ordinal number used to access an array element ( Array of The subscript is from 0 At the beginning

var arr = [" The small white "," Xiao Huang "," Little black "," Xiaohong "]

Reference no. :      0         1        2        3

Format :        Array name [ Reference no. ]   

  Four 、 Traversal array

        After reading the introduction above , I believe you have a preliminary understanding of arrays , So how can we get all the elements in the array ? That's what we're going to talk about next   Traverse  .

Traverse : That is to access every element in the array from beginning to end .

       4、1 Utilization cycle , Traversal array

var arr = ["red","green","blue"];
    for (var i = 0; i < arr.length; i++){
        console.log(arr[i])
    }

        Be careful : Because our array index number uses 0 At the beginning , therefore i The initial value of must be 0 

         4、2 for...in Traversal array

for(var k in  Array ){
    k  Subscript subscript 
     Array [k]   The element corresponding to the subscript 
}

expand : Bubble sort

        Bubble sort : It's an algorithm , Arrange and display a series of arrays in a certain order ( From large to small or from small to large ).

        The idea of bubble sort : Compare two elements at a time , If they are in the wrong order , Just exchange them .

Case study

var arr = [5,4,3,2,1]
    for(var i = 0;i <= arr.length - 1;i++){  // The outer loop controls the number of trips ( Loop through the entire array )
        for(var j = 0;j <= arr.length - i -1;j++){  // Inner loop control times 
         //  Use  if  Judge , Exchange the values of two variables ( What we use here is : Exchange the values of the current two variables through the third variable )
            if(arr[j] > arr[j + 1]){
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
console.log(arr);

5、 ... and 、 Array API

        The use of arrays can greatly facilitate our use and operation of data , And the official has also encapsulated a large number of array related API(JS Predefined functions or methods in ), To provide our development efficiency .

API purpose remarks
toString() Convert an array to a string The elements are separated by commas
join() Convert an array to a string You can specify between elements Separator symbol , The default is comma ” Separate
reverse() Flip array
sort() Sort the array The default is Unicode Sort
concat(arr1,arr2,arr3,...) Splicing multiple arrays

arr1,arr2 Represents the array to be spliced

Return value : Returns the spliced array , The original array will not change

indexOf() Check whether there is an element in the array Return value : Returns the subscript , If you can't find it , return  -1
slice(start,end) Intercept array elements

start: The starting subscript ;end: Ending subscript , It doesn't contain end In itself

end It's empty , Cut to the end ;end It's a negative number , Said the bottom

Return value : Returns the intercepted element , The original array will not change

splice(start,end) Delete array elements

start: The starting subscript ;count: Deleted length

count It's empty , Indicates deletion to the end ;count It's a negative number , Said the bottom ;count by 0, Indicates to insert

Return value : Return deleted elements , The original array will change

push() Add elements at the end of the array Return value : return - Length of array , The original array will change
pop() Delete an element at the end of the array Return value : Deleted elements , The original array will change
unshift() Add an element at the beginning of the array Return value : Returns the length of the array , The original array will change
shift() Delete an element at the beginning of the array Return value : Return deleted elements , The original array will change

         In our usual development process , If we can skillfully use the correlation of writing arrays API, Then our development efficiency will be greatly improved , If I feel that the above introduction is not very detailed , Then you can go to the following website , There is a specific introduction

Array - JavaScript | MDN

  6、 ... and 、 Higher order functions of arrays

        6、1 every  Determine whether each element of the array meets the conditions

every( function ): Array of Every element Will be processed through functions , Determine whether the specified conditions are met

Function receive 3 individual Parameters  value、index、array ( Fixed order , The parameter name is optional , Unused parameters may not be written ) Pictured :

 

every() Of Return value : Each element of the array , After function processing , All meet the requirements , Then return to  true, As long as one does not meet the conditions , Then return to  false .

  Case study 1: Determine whether each element in the array is a positive number

  <script>
      // every:  Every element of the array meets the condition 
      let nums = [11, -2, 45, 767, 32, 4, 5]
      //  Determine whether the array has   every last   All positive numbers. 
      // every( function ):  Each element of the array will be processed by functions ,  Determine whether the specified conditions are met 
      //  Function receive 3 Parameters ,  It's a fixed sequence ,  The parameter name is optional 
      var res = nums.every((value, index, array) => {
        console.log(' value value:', value)
        console.log(' Subscript index:', index)
        console.log('array:', array)
        //  Conditions :  The value is a positive number  > = 0
        return value > 0 //  Meet the conditions   return true
     })
      // every Result :  Each element of the array ,  After function processing   All are true,  The end result is true,  It is false
      console.log(res ? ' All positive numbers. ' : ' Not all positive numbers ')
    </script>

  Case study 2: Determine whether each element in the array is odd

<script>
var a = [11, 22, 33, 44, 55]
      //  Judge : a Are all odd numbers in 
      var res = a.every((value, index, array) => {
        //  Odd number :  Yes 2 Remainder   result 1 Of 
        return value % 2 == 1
     })
      //  Omit 1:  Parameters not used in the method body ,  You can omit it 
      res = a.every(value => {
        return value % 2 == 1
     })
      //  Omit 2:  Method body of arrow function ,  There is only one line ,  Omit {return }
      res = a.every(value => value % 2 == 1)
      //  Omit 3:  Implicit type conversion  0 false  1 really 
      res = a.every(value => value % 2)
      console.log(res ? ' It's all odd ' : ' Not all are odd numbers ')
      var b = [32, 43, 12, 45, 67]
      //  Judge b Whether each value in is greater than 20
      var res = b.every(value => value > 20)
      console.log(res ? ' all >20' : ' Feidu >20')
</script>

        6、2 some( In the array At least one Meet the conditions )

some(): As long as the array There is one The element satisfies the condition , Just go back to true

Function receive 3 individual Parameters  value、index、array ( Fixed order , The parameter name is optional , Unused parameters may not be written ) , and every The same parameters as .

some() Of Return value : Array As long as there is one Satisfied , some The result is that true, None , Just go back to false

  Case study : Determine whether there are even numbers in the array

  <script>
      // some:  At least one   Satisfied 
      var nums = [11, 22, 3, 5]
      //  To determine if there is   even numbers 
      var res = nums.some(value => {
        //  All the parameters   Same as  every  Method 
        return value % 2 == 0
     })
      //  Simplify grammar :
      res = nums.some(value => value % 2 == 0)
      //  As long as there is one in the array that meets the condition , some The result is that true
      console.log(res ? ' There are even numbers ' : ' No even number ')
</script>

        6、3 map( An array of map )

map(): mapping -- Each value of the array , After the transformation, a new array is formed

Function receive 3 individual Parameters  value、index、array ( Fixed order , The parameter name is optional , Unused parameters may not be written ) , and every The same parameters as .

map() Of Return value :map() Method Returns a new array , The element in the array is the value after the original array element calls the function .

<script>
    // map:  mapping -- Each value of the array ,  After the transformation, a new array is formed 
    var nums = [1, 2, 3, 4, 5, 6]
    //  Put each value of the array  x2,  Get the new array 
    var res = nums.map(value => {
      return value * 2
    })
    //   Simplify writing  return The return value of ,  Will form a new array 
    res = nums.map(value => value * 2)
    console.log('res:', res)
</script

        6、4 filter( Array filtering )

filter(): Array filtering —— Filter the qualified elements and return a new array , The original array remains the same

Function receive 3 individual Parameters  value、index、array ( Fixed order , The parameter name is optional , Unused parameters may not be written ) , and every The same parameters as .
filter() Of Return value : When filter Filter out qualified values , Meeting Returns a new array

Be careful :filter Empty arrays will not be detected

Case study 1: Find all even numbers

 <script>
      // filter:  Filter --  Combine the elements that meet the conditions into a new array 
      var nums = [11, 2, 43, 65, 76, 8, 87, 9]
      //  Find all even numbers 
      var res = nums.filter(value => {
        return value % 2 == 0
     })
      //  simplify 
      res = nums.filter(value => value % 2 == 0)
      console.log('res:', res)
</script>

  Case study 2: Find out who meets the requirements

<script> 
var emps = [
       { name: 'mike', salary: 8999, age: 39 },
       { name: 'lucy', salary: 6999, age: 31 },
       { name: 'tom', salary: 4999, age: 32 },
       { name: 'john', salary: 3999, age: 25 },
     ]
      //  Mission 1:  Find out all   Salary   Greater than 5000 People who 
      var res = emps.filter(value => value.salary > 5000)
      console.log(res)
      //  Mission 2:  Find out all   Age   Less than 35  People who 
      var res = emps.filter(value => value.age < 35)
      console.log(res)
</script>

        6、5 forEach( Traversal array , Instead of for loop )

forEach(): Simply traverse the array , Used to replace for loop

Function receive 2 Parameters :value,index( Usage and every The method is consistent )

forEach no return value

  Case study : utilize forEach Traversal array , And modify the values in the array

 <script>
      // forEach:  Simply traverse the array ,  Used to replace  for  loop 
      var names = ['mike', 'lucy', 'lily', 'john']
      // forEach no return value 
      names.forEach((value, index) => {
        console.log('value:', value)
        console.log('index:', index)
     })
      // for Loop through array writing :  Too complicated   So basically not 
      // for (let i = 0; i < names.length; i++ ) {
      //   let value = names[i]
      // }
      var emps = [
       { name: 'mike', salary: 8999, age: 39 },
       { name: 'lucy', salary: 6999, age: 31 },
       { name: 'tom', salary: 4999, age: 32 },
       { name: 'john', salary: 3999, age: 25 },
     ]
      //  Take everyone's salary +1000,  Age +2
      emps.forEach(value => {
        // +=  Full write format of 
        //  utilize  =  Assignment symbol ,  To modify the   Original value 
        value.salary = value.salary + 1000
        value.age += 2
     })
      console.log(emps)
  </script>

        6、6 reduce( inductive 、 Merge )

reduce(): inductive , Merge —— You can put the elements in the array , Sum it up into a value

Function receive 2 Parameters :sumvalue(sum: Initial value ,value: The value of the current element )

reduce() Writing :

  var res = nums.reduce((sum, value) => {
        //  Parameters 1: sum,  The result after each accumulation 
        //  Every time I traverse ,  Add up the value to sum.  The return value is new sum The sum of the 
        return sum + value
     }, 0)

reduce() Simplification of :

res = nums.reduce((sum, value) =>sum + value, 0)

  Case study : Calculated total price

 <script>
      var products = [
       { name: 'iphone1', count: 3, price: 8888 },
       { name: 'iphone2', count: 5, price: 2888 },
       { name: 'iphone3', count: 1, price: 4888 },
       { name: 'iphone4', count: 13, price: 6888 },
     ]
      //  Calculate the total amount 
      // 0  yes  sum  The default value of , sum=0
      var total = products.reduce((sum, value) => {
        //  Multiply and divide first   Add and subtract 
        return sum + value.count * value.price
     }, 0)
      console.log(total)
 </script>

原网站

版权声明
本文为[Xiao Zhang, run quickly.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130553106228.html