编程知识 cdmana.com

Array method

A method of adding items to an array

var ary =[1,2,3]

  • Using arrays length Property adds... To the end of the array
    • ary[ary.length]=4; Add a number to the end of the array 4
  • push Method : Add... To the end of the array , If you pass more parameters, you will add more
    • push The return value of is the changed array length
var ary = [1, 2, 3];
ary.push("push Come in ",2,3,4);
  console.log(ary);[1, 2, 3, "push Come in ", 2, 3, 4]  length: 7
 Copy code 
  • unshift Add... To the beginning of the array , Several items of transmission parameters , Just add a few items
    • Will change the index of the original array
    • unshift The return value of is the length of the changed array
ary.unshift(" I am a unshif Add in ",8)
 Will add... In front of the array 
 Copy code 

Method for deleting items from an array

  • pop Delete the last item of the array
    • pop The return value of is the deleted item
    • Will change the original index of the array
var ary1 = [4, 5, 6];
 var res=ary1.pop();
console.log(res); The output of is 6
 Copy code 
  • shift Delete the first item in the array
    • Will change the index of the original item of the array
    • The return value is the deleted item
 var ary1 = [4, 5, 6];
console.log(ary1);
console.log(ary1.shift());   The result is 4
 Copy code 
  • delete How to delete key value pairs , You can also delete the corresponding item in the array
    • Does not change the index of the original item in the array
delete ary1[1];
[4, empty, 6]
//length still 3;
 Copy code 
  • length== Delete the last item in the array
    • Here we use the operation length To change the array
    • Output depends -- The location of

splice You can add, delete, or change

The first parameter indicates which index to start with , The second parameter indicates how many items to delete , Start with the third parameter to indicate the added item

  • splice(n,0,x) When the second parameter is 0 when , Just don't delete , And there is a third item , Is to increase , It's indexing n Add... In front of
  • splice(n,m) From the index n To delete m Elements , The return result is in the form of a new array , Store the deleted content
  • splice(n,m,x) From the index n To delete m Elements , The added elements are placed in the index n It's about
  • The return value is an array , The content is the deleted item
  • ary2.splice(0,0," Added items "); From the index 0 It is not deleted at first, and the third parameter is added in the first item
  • ary2.splice(0,1," Modified item "); From the index 0 Delete an element at the beginning , And add the third element to this location

Verify whether an item is in the array

  • var ary2 = [" Chen ", " macro ", " Chapter "," Chen "];

indexOf Verify whether an item is in the array , Return value if yes Negative one It's not in the array , Look back before ; If the corresponding index is returned in the array

var res2 = ary2.indexOf(" Xiao Ming ");// If there is no such item in the array, the output is -1
var res2 = ary2.indexOf(" Chen ");//=>0
 Copy code 

lastIndexOf Look backwards

var res3=ary2.lastIndexOf(" Chen ");//=>3
 console.log(res3);// The output is 3   Because it's looking back and forward , The last Chen's index is 3 So the output is three 
 Copy code 

includes Verify that the item is not in the array

There is a return true, No return false

var res4 = ary2.includes(" Chen ")

console.log(res4);

Do not change the method of the original array

  • concat Array splicing , Put multiple arrays ( Or multiple values ) Finally, it is spliced into an array , The original array will not change , The returned result is the spliced new array
    • var ary1=[4,5,6," Chen "];
    • If the parameter is an array , Will strip off one layer of the array []
    • Multiple parameters can be passed , All stitched together
    • var res=ary1.concat([" macro "," Chapter "]);
    • If you don't pass any parameters, you are cloning the array
      • var res =ary1.concat(); The output is [4,5,6," Chen "]
  • slice(n,m) From the index n Start copying to index m It's about ( Excluding the index m) Return the found content as a new array , The original array will not change .
var ary =[1,2,3,4,5,6];
var res =ary.slice(0,4);
 console.log(ary);// Output the original array 
 console.log(res);// Output [1,2,3,4], From the index 0 Start copying to index 4 It's about , Excluding the index 4
 Copy code 
  • slice(-3,-2)
    • From the index (-3+length) To (-2+length) barring -2+length
var ary =[1,2,3,4,5,6];
var res =ary.slice(-3,-2);
 console.log(ary);// Output array 
 console.log(res);// Output 4, because 6-3=3,6-2=4(3,4)
 Copy code 
  • Clone array
    • var res =ary.slice(0), It can be understood as finding every item in the original array , Returns... As a new array , Clone the array , The resulting new array and the original array are two different heaps , But the stored content is the same
    • console.log(ary);
    • console.log(res);
    • If the second parameter is greater than length Big is straight to the end

Convert an array to a string :

  • toString(); Put every item in the array according to “ Comma separated ”, Splice into the corresponding string , The original array will not change
let arr =[10,20,30,40,50,60,70]
console.log(arr.toString());// The output is '10,20,30,40,50,60,70'
 Copy code 
  • join([char]); Specify the separator
    • join Concatenate each item in the array with characters , The return is a string
  var arr =[1,2,3]
        // join Concatenate each item in the array with characters , The return is a string 
        var res =arr.join("+");
        // var res =arr.join();// If you don't pass the parameters , By default, they are concatenated with commas , amount to toString()
        console.log(res);
       
 Copy code 
  • eval You can turn a string into an expression to execute
    • If the string above can become JS Expression execution , Represents the sum of each item of the array
 eval  You can turn a string into an expression to execute 
   console.log(eval(res))
 Copy code 

Array sorting

  • reverse Sort each item in the array upside down
  • Sort array
  • Without passing parameters , It will only be sorted according to the first place
  • Numbers are arranged from small to large
  • The letters are in coded order
     console.log(res);


        var res2=ary.sort((a,b)=> {

            console.log(a,b);
            return a-b;// Ascending 
            // return b-a;// Descending 
        })
        console.log(ary,res2);

        var arrobj=[
            {name:"q",age:12},
            {name:"qw",age:22},
            {name:"er",age:11},
            {name:"sdf",age:1}
        ];
        arrobj.sort((a,b)=>{
            return a.age-b.age;
        })
        console.log(arrobj);
 Copy code 

String method

  • indexOf
  • lastindexOf
  • includes
  • substr(n,m) From the index n Began to intercept m Characters , Negative numbers are not supported
  • slice(n,m) From the index n Start intercepting to index m, barring m, Support negative numbers
  • substring(n,m) From the index n Start intercepting to index m, barring m
var str2 = ' Family countdown ';
   var res = str2.substr(0, 3);
   var res1 = str2.substring(2, 5);
   var res2 = str2.slice(2, 5);
   console.log(res1,res,res2)
 Copy code 

Gets the character of the string related index

  • charAt Gets the character of the string related index
  • charCodeAt Gets the character of the string related index , Turning characters into ASCII The numbers in the table
  • String.fromCharCode hold ASCII The numbers in the table are converted into characters
var str =' The whole family will be seven or seven '
        var res =str.charAt(0);
        var res1 =str.charCodeAt(0);
        console.log(res1);
        console.log(String.fromCharCode(19968));
        console.log(str[0]);
 Copy code 

Capitalize letters

  • toUpperCase() All letters are capitalized
  • toLowerCase() Turn all letters into lowercase
var abc='abcdefg';
        console.log(abc.toUpperCase());
        console.log(abc.toLowerCase());
 Copy code 

Implement initial capitalization

  • 1. Get the initials first , Then capitalize
  • 2. Get the remaining characters except the initials , And then put them together
var res =abc.substring(0,1).toUpperCase()+abc.substring(1);
        console.log(res);
 Copy code 

The specified character splits the string into each item in the array

\

\

       // split   A specified character splits the string into each item in the array 
        // var str ='1+2+3';
        // var res =str.split("+");//【1,2,3】
        // console.log(res);

        var str2 ='https://www.baidu.com/s?wd=JS&rsv_spt=1&a=1&b=2'
        var res4 = str2.split("?");
        var ary =res4[1].split("&");
        // console.log(ary);
        var obj={};
        ary.forEach((item,index)=>{
            // item  Is every item in the array 
            // index  Is the index of the item 
            // console.log(item,index);
            var inner =item.split('=');
            // var shuxingming=inner[0];
            // var shuxingzhi=inner[1]
            // obj[shuxingming]=shuxingzhi;
            obj[inner[0]]=inner[1];
            console.log(obj);
        })
 Copy code 

Iterative methods commonly used in arrays

  • foreach([ function ])
    • Traverse every item in the array ( How many items are in the array , How many times will the function be executed in succession , Every function executed , You can get this item and the corresponding index in the function )
arr.forEach(function(item,index){
    // This function will be executed in a loop five times ( There are five items in the array )
    //item: Currently traversing the contents of this item 
    //index: Index of current item 
console.log(item,index)

})
 Copy code 

The way arrays are summed

  • join
let arr =[10,20,30,40,50]
console.log(eval(arr.join('+')));// If a non significant number appears in the array , The final result is NaN
 Copy code 
  • adopt for loop
let total=0;
for(let i=0;i<arr.length;i++){
                  total+=arr[i];
   }
 console.log(total)
 Copy code 
  • forEach Method
let total=0;
arr.forEach(function(item.index){
item =Number(item);
if(isNaN(item)===false){
total+=item;

}
})
console.log(total);
 Copy code 
  • map Method :forEach Return values are not supported , and map Can be in forEach Support return values based on , Replacing the value of each item in the original array is called the new value , Finally, it is stored in a new array , But the original array is unchanged
let arr =[10,20,30,40,50];
let reault=arr.map(function(item,index){
    // This function will be executed in a loop five times ( There are five items in the array )
    //item: Currently traversing the contents of this item 
    //index: Index of current item 

// What is returned in the function , Is to replace the current item in the array with something 
return item;
})
console.log(result);
 Copy code 

版权声明
本文为[Chen Hongzhang]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/09/20210909131415424x.html

Tags array method
Scroll to Top