Zero foundation to quickly master JavaScript array, deep copy and shallow copy

catalogue

1, Array basis

1. Create an array

1. Use Array constructor to create

2. Use literal method to create

3. Application: create an array containing 1-100

  2. Array traversal

Two ways f (for, for in loop) of traversal

2, The array realizes deep copy and shallow copy

1. Deep copy and shallow copy

2. Deep copy and shallow copy of array

3, An array of iteratable objects or classes is converted to a true array

1. The difference between iteratable objects and class arrays

Iteratable object

Array like

2. Convert iteratable object or class array to true array

Array.from() method for conversion (ES6)

Use the for in method to put members into a new array  

4, Array detection

instanceof operator

Array.isArray() method

5, Serialization and deserialization of arrays

6, Prototype method of array

1. Constructor method

2. Prototype method

Stack and queue method (change the original array)

Sorting method

Operation method

Location method

Iterative method

1, Array basis

ECMAScript array is a sequence table and a collection of multiple values.

It has the following characteristics:

Each item can hold any type of data. (string, value, array) arrays generally place the same type of data

The size of the array can be adjusted dynamically.

Array length property: readable and writable. You can remove items from the end of the array or add new items to the array by setting the value of length

The array in js is a collection that can store values of any data type, the elements of the array can be of any data type, and the length of the array can be adjusted dynamically.

1. Create an array

1. Use Array constructor to create

//Array creation
//Create using the Array constructor
var arr1 = new Array(5);//The number in () indicates the length of the array initialized at creation
arr1[0] = 'zhangshan';
arr1[1] = 'lisi';
arr1[2] = 'wangwu';
console.log(arr1);//['Zhangshan', 'Lisi', 'Wangwu', < 2 empty items > (the two items are null)]
console.log(arr1.length);//5

2. Use literal method to create

//Literal creation array is [] object is {}
var arr2=['zhangshan','lisi','wangwu'];
console.log(arr2);//[ 'zhangshan', 'lisi', 'wangwu' ]

3. Application: create an array containing 1-100

The push() method is to add to the bottom of the array, which means to add to the bottom of the array
The unshift() method is to add to the stack top of the array, which means to add to the head of the array

//Create an array containing 1-100
//Method 1: VAR num = [1,2,...]
var nums = [];
for(var i=0;i<100;i++){
    nums[i] = i+1;
}
console.log(nums);//1-100

//Output all even numbers from 1-100 from small to large
var nums = [];
for(var i=0;i<100;i++){
    if(i%2==0){nums.push(i)}
}
console.log(nums);
//Output 1-100 all even numbers from large to small
var nums = [];
for(var i=0;i<100;i++){
    if(i%2==0){nums.unshift(i)}
}
console.log(nums);
//Output 1-100 odd numbers from small to large
var nums = [];
for(var i=0;i<100;i++){
    if(i%2!=0){nums.push(i)}
}
console.log(nums);

 

  2. Array traversal

Two ways f (for, for in loop) of traversal

//Array traversal (extracting each member once) extracts array members in a loop
//for loop
var nums = [1,2,3];
for(var i=0;i<nums.length;i++){
    console.log(nums[i]);//1,2,3
//You can do some operations. Num [i] = 'number:' + num [i];
}
console.log(nums);//[1,2,3]

//for...in loop
for(var k in nums){
    console.log(nums[k]);
}

2, The array realizes deep copy and shallow copy

1. Deep copy and shallow copy

Mainly for the reference data type parameter, shallow copy means to copy only the reference address, and deep copy means to clone the object

How to implement deep copy:

1. JSON serialization      : JSON.parse(JSON.stringify(obj))

2. Object.assign() copy     : Object.assign({},   obj1); / / deep copy

2. Deep copy and shallow copy of array

Shallow copy (array): (changes the original array)

If array A is re assigned to array B and the attribute value in array B is changed, the value in array a will also change.

Deep copy (array): (the original array will not be changed)

(1) Use slice() and concat() methods to implement deep copy

(2) Using loop implementation

//Array is also a reference data type {}
var arr3 = [1,2,3];
var arr4 = arr3;
arr4[3] = 4;
console.log(arr3);//[1, 2, 3, 4] shallow copy

//Array implementation deep copy
var arr5 = [];//Create a new array, traverse the members of array 3 and add them to array 5 one by one
for(var k in arr3){
    arr5.push(arr3[k]);
}
var arr6 = arr3.concat(5,6);//Array splicing function, return new array [1,2,3,5,6]
arr6.push(4) //[1,2,3,4,5,6] does not affect the copied array

3, An array of iteratable objects or classes is converted to a true array

1. The difference between iteratable objects and class arrays

Iteratable object

An iteratable object is a generalization of an array. That is, any object can be customized as an object that can be used in a for..of loop. Arrays and strings are iterative. Technically, an object is not an array, but a set (list, set) representing something. for..of is a good syntax that can traverse it

Iterable, as mentioned above, is an object that implements the Symbol.iterator method (a built-in symbol for making objects iteratable).

Array like

Array like are objects with index and length attributes, so they look like arrays

var obj = {
    0:'zhangsan',
    1:'lisi',
    2:'wangwu',
    length:3
}

Iteratable objects and array like objects are usually not arrays. They do not have methods such as push and pop

2. Convert iteratable object or class array to true array

Array.from() method for conversion (ES6)

The Array.from method accepts the object, checks that it is an iteratable object or class array object, creates a new array, and copies all the elements of the object to the new array. j then we can operate on the array as a real array

//Converts an iteratable object or class array object to a true array
var obj = {
    '0':'zhangshan',
    '1':'lisi',
    '2':'wangwu',
    'length':3
}
console.log(obj);//{ '0': 'zhangshan', '1': 'lisi', '2': 'wangwu', length: 3 }
var arr_obj = Array.from(obj);
arr_obj.push('zhaoliu');
console.log(arr_obj);//[ 'zhangshan', 'lisi', 'wangwu', 'zhaoliu' ]

Use the for in method to put members into a new array  

4, Array detection

How to detect that a data is an array type

instanceof operator

Array.isArray() method

//How to detect that a data is an array type
//instanceof operator
var arr = [1,2,3];
var obj_arr = {'0':1,'length':1}//Class array
var str = 'hello'//It is both a class array and an iteratable object
console.log(arr instanceof Array); //true
console.log(obj_arr instanceof Array); //false

if(!(obj_arr instanceof Array)){
    obj_arr = Array.from(obj_arr);
}//Check whether the class array is a true array. If not, it will be turned into a true array
console.log(obj_arr);//[1]


//Array.isArray() determines whether a data is an array
console.log(Array.isArray(arr));//true

console.log(typeof arr);//The object reference data type typeof is object

  5, Serialization and deserialization of arrays

Array serialization      JSON.stringify()

Array deserialization     JSON.parse()

//Serialization and deserialization of arrays
var arr = [{id:0,
            name:'zhangshan',
            age:10,
            class:'4-1',
            sex:'nan'},{
                id:1,
                name:'lisi',
                age:10,
                class:'4-1',
                sex:'nan' 
            }];
var arr_str = JSON.stringify(arr);//Convert array to json string
console.log(arr_str);//[{"id":0,...,"sex":"nan"},{"id":1,...,"sex":"nan"}]

var new_arr = JSON.parse(arr_str);//Returns the json string to an array
console.log(new_str);//[{ id:0, ...,sex:'nan'},{id: 1, ..., sex: 'nan' }]

  Encapsulate data into tables

toString() returns array items as comma separated strings by default

join() uses the specified string to separate array strings

split() deserializes and returns a new array

//Encapsulate the data into a table data (3 * tr > 5 * td > content)
var num_arr = [1,2,3];
//The array is converted into a string through toSting(). By default, the string is split
var str = num_arr.toString();
console.log(str);//1,2,3
//Convert the array into a string through a character splicing through join()
var str2 = num_arr.join('|');//1|2|3
console.log(str2);
//You can deserialize through split() to return a new array
var new_arr = str.split(',');//String method
console.log(new_arr);//[ '1', '2', '3' ]

6, Prototype method of array

1. Constructor method

Array.isArray()      Used to determine whether a variable is an array object

Array.from()          Create a new array instance from a class array object or an iteratable object.

Array.from('foo');   // [ "f", "o", "o" ]
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);    // [ "foo", "bar", "baz" ]

Array.of()/New Array() creates a new array instance based on a set of parameters, and supports any number and type of parameters.

Array.of(7);       // [7]
New Array(7);      //7 null array length=7
Array.of(1, 2, 3); // [1, 2, 3]

2. Prototype method

Stack and queue method (change the original array)

Stack   LIFO (Last-In-First-Out)   First in and last out

pop() removes the last item in the array and returns it, while reducing the length of the array by one,

push()   You can accept parameters of any type, add them to the end of the array one by one, and return the length of the array

Queue    FIFO (First-In-First-Out)   First in first out

shift()    Removes the first item in the array and returns it, reducing the length of the array by one

unshift()   Add any item to the front of the array and return the length of the array

 

//Stack and queue methods will change the original array
var arr = [1,2,3];
//arr.push append element at the end
arr.push(4);//[1,2,3,4]
//arr.pop delete the last element
arr.pop();[1,2,3]
//arr.unshift places the element before the first item
arr.unshift(0);[0,1,2,3]
//arr.shift deletes the first element
arr.shift();[1,2,3]
console.log(arr);

Sorting method

sort

  reverse()   Reverse the order of array items and change the original array

arr.reverse();//3,2,1
console.log(arr);

 sort()

Default sorting: this method calls the toString() method of each array item, and then sorts according to the character sequence

Custom sorting:

a. This method can accept a comparison function as a parameter, and the comparison function has two parameters

b. Returns a negative number if the first argument precedes the second argument

c. Returns a positive number if the first argument follows the second argument

//Sort sort, starting from the first digit on the left, and then sort bit by bit to the right
var num_arr = [1,33,113,223,23,111];//[ 1, 111, 113, 223, 23, 33 ]
console.log(num_arr.sort());
//sort can complete the normal sorting function. You need to pass in a sorting function
console.log(num_arr.sort(function(v1,v2){
            if(v1>v2)
                return 1;//Do not change position
            else if(v1<v2)
                return -1;//Change position
            else
                return 0;
}));//[ 1, 23, 33, 111, 113, 223 ]

 

Sorting algorithms: bubble sort, quick sort, insert sort and select sort

//Write a sort function: bubble sort
function mysort(arr){
    for(var i=0;i<arr.length-i-1;i++){//How many times
        for(var j=0;j<arr.length-i-1;j++){
            if(arr[j]<arr[j+1]){
                var temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    console.log(arr);
}
mysort([2,3,7,1,4]);

ps: Here are ten commonly used sorting methods, with moving pictures, vivid and vivid

  Operation method

Interception and splicing of arrays

Interception method

 concat()  

Array splicing: first create a copy of the current array, and then add the received parameters to the end of the copy to return the copy without changing the original array

//Interception and splicing of arrays
//concat returns the spliced new array
var arr1=[1,2,3];
var arr2=arr1.concat(4,5,6);
console.log(arr2);//[ 1, 2, 3, 4, 5, 6 ]

 slice()  

Array cutting can accept one or two parameters (return the start position and end position of the item). When accepting a parameter, all items from the position specified by the parameter to the end of the current array. When two parameters are accepted, the item between the start and end, but the item without the end position, that is, before the end of the index. Do not change the original array

var arr2 = [ 1, 2, 3, 4, 5, 6 ];
//slice array cutting; Returns the intercepted new array
var arr3 = arr2.slice(0,3);//Returns the part before ending the index
console.log(arr3);//[ 1, 2, 3 ]

 splice()  

Inserting data into the middle of an array always returns an array containing items removed from the original array.

Delete: specify two parameters (starting position, number of items to delete)

Insert: specify three parameters (starting position, 0, any number of items to insert)

Replace: specify three parameters (starting position, number of items to delete, any number of items to insert)

var arr2 = [ 1, 2, 3, 4, 5, 6 ];

//splice(): receive three parameters (start_index,length, replacement or additional element).
//It will directly change the original array and return the selected elements, which can be replaced, added and deleted
arr2.splice(2,3,8,8,8);//Replace 3 elements with 8,8,8 starting from the value with subscript 2
console.log(arr2);// [1, 2, 8, 8, 8, 6 ]

var res=arr2.splice(0,2,66,66);//Create a new array res to store the replaced elements in arr2
console.log(arr2);//[ 66, 66, 8, 8, 8, 6 ]
console.log(res);//[ 1, 2 ]

arr2.splice(2,3,8);//Three elements are extracted from the element with subscript 2, but only one 8 is added, which is equivalent to deletion
console.log(arr2);//[ 66, 66, 8, 6 ]

arr2.splice(0,0,8);//Not extracted, added one, relative to append
console.log(arr2);//[ 8, 66, 66, 8, 6 ]

Location method

Index method

 indexOf()  

Search backward from the beginning of the array. Use the congruent operator. If the element is not found, return - 1. The first parameter is the item to find, and the second parameter (optional) is the index start position

 lastIndexOf()  

Look forward from the end of the array and use the congruent operator. If the element is not found, return - 1. The first parameter is the item to find, and the second parameter (optional) is the index start position

//Location method 
//indexOf is more suitable for judging whether there is a member in an array
var arr = [1,2,3,4,5,4,3,2,1];
console.log(arr.indexOf(1));//0 finds the specified element from the beginning, and exits when it is found
console.log(arr.lastIndexOf(1));//8 find from the end
console.log(arr.indexOf(6));//- 1 not found

//How to de duplicate an array
function qc(arr){//Encapsulate functions
var new_arr=[];
for(var k in arr){
    if(new_arr.indexOf(arr[k])==-1)//If not, put in a new array
    new_arr.push(arr[k]);
}
// return new_arr
console.log(new_arr);
}

  Iterative method

      every: runs the given function for each item in the array. If the function returns true for each item, it returns true

//Iterative method of array
//every   true will be returned only when all members are satisfied (judge whether a group of students meet the age of 18)
var ages = [19,20,21,18,17,19,20];
var res=ages.every(function(v,index,arr){
    return v>=18;//Returns a Boolean value
})
console.log(res);//false

      some: runs the given function for each item in the array. If the function returns true for any item, it returns true

//If only one member of some is satisfied, it will return true (judge whether a group of students are 18 years old)
var ages1=[19,3,5,7];
var res=ages1.some(function(v,index,arr){
    return v>=18;//Returns a Boolean value
})
console.log(res);//ture

       filter: run the given function for each item in the array, and returning the function will return an array of true items

//The filter filter obtains some qualified members (18-year-old members from a group of students)
var ages1=[19,3,5,19,334,3,7];
var res=ages1.filter(function(v,index,arr){
    return v>=18;//Returns a Boolean value
})
console.log(res);//19,19,334

map: run the given function for each item in the array and return the array composed of the results of each function call

//map method, traversal method, with return value (after one year, add one to the age of all students)
var res=ages1.map(function(v,index,arr){
    return v+1;//Results after operation
})
console.log(res);//[20, 4, 6, 20, 335, 4, 8]

           forEach: runs the given function on each item in the array, and the method does not return a value

//foreach method, no return value, traverse the array members once, do some operations, and there is no return value
var new_arr=[];
ages1.forEach(function(v,index,arr){
    new_arr.push(v+1);
})
console.log(new_arr);//[20, 4, 6, 20, 335, 4, 8]

Tags: Javascript Permutation array

Posted on Mon, 20 Sep 2021 16:31:27 -0400 by sogno