JavaScript high programming -- Array type

Posted by danj on Sun, 30 Jan 2022 03:36:16 +0100

Create array

The Array constructor creates an Array

  1. Create an empty array
var arr = new Array();//[]
arr.length //0
  1. Create an array with a length of 10
var arr = new Array(10)
arr.length //10
  1. Creates an array containing the specified element
//The data type of each element of the array in ECMAScript can be different
var arr = new Array(1,2,'a',4,'b')//[1, 2, "a", 4, "b"]
arr.length //5

Note: calling the Array constructor to create an Array can also omit the new operator, and the results are the same.

Literal create array

var arr = [1,2,3]; //Create an array of 3 elements
var arr = [];      //Create an empty array

Unlike objects, Array constructors are not called when creating arrays with literal values

from() and of() create arrays

Array.from() can convert any structure data that can be iterated into an array

  1. Convert string to array
var str = Array.from('abcd')//["a", "b", "c", "d"]
  1. Convert map structure data to array
var map = new Map().set(1,2).set(3.4) 
var mapArr = Array.from(map) //[[1,2],[3,4]]
  1. Convert set structure data to array
var set = new Set().add(1).add(2).add(3)//{1, 2, 3}
var setArr = Array.from(set);//[1, 2, 3]
  1. Shallow copy of existing arrays
var a1 = [1,2,3];
var a2 = Array.from(a1) //[1, 2, 3]
  1. The arguments object is converted to an array
function getArgsArray(){
	console.log(arguments,'arguments'); //[1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] "arguments"
	return Array.from(arguments);
}
getArgsArray(1,2,3,4) //[1, 2, 3, 4]
  1. Convert objects with specific properties to arrays

Object with specific attribute: object with attribute name number and containing attribute name length

var obj = {1:'aa',2:'bb',3:'cc',length:4};
var arr = Array.from(obj); //[undefined, "aa", "bb", "cc"]

Defines an object obj, in which the length attribute value is 4, through array From() is converted to an array because the index value 0 is missing. The index is populated as undefined by default.

var obj = {name:'zl',1:'aa',2:'bb',3:'cc',length:4};
var a = Array.from(obj);//[undefined, "aa", "bb", "cc"]

A name attribute is added, which is automatically omitted by default. You can try to verify it yourself in other special cases

  1. Array. Other parameters of from()
    Array.from() can also accept the second parameter (mapping function) and the third parameter (specifying the value of this in the mapping function). (Note: this value is not applicable in the arrow function)
var a1 = [1,2,3,4];
var a2 = Array.from(a1,(i)=>i*2);//[2, 4, 6, 8]
var a3 = Array.from(a1,function(i){return i*this.num},{num:3})//[3, 6, 9, 12]

If you do not use the second mapping function parameter and want to double each element of array a1, you can call array from(). Map (), so you need to create an additional intermediate array

let a1 = [1,2,3,4];
let a2 = Array.from(a1).map((i)=>i*2);//[2, 4, 6, 8]
  1. Array. The of() function converts a set of parameters into an array
var a = Array.of(1,2,3,4)//[1, 2, 3, 4]
var aa = Array.of('11','22','33','44')//["11", "22", "33", "44"]

Array index

length attribute

The length attribute in the array is not read-only. You can delete or add elements at the end of the array by modifying the value of length

var a = [1,2,3,4];
a.length = 10; //add to
console.log(a[9])//undefined
a.length =2; //delete
console.log(a)//[1, 2]
console.log(a[3]) //undefined

Detection array

Judgment array

Array.isArray() determines whether the data is an array

Array.isArray([1,2,3]) //true

Iterator method

The Array prototype exposes three methods to retrieve the contents of the Array, keys(),values(),ertries(), all of which return iterators

keys()

Returns the iterator of the array index

var nums = [1,2,3,4];
const aKeys = Array.from(nums.keys())//[0, 1, 2, 3]

values()

An iterator that returns the value of an array element

var nums = [1,2,3,4];
const aValues = Array.from(nums.values())//[1, 2, 3, 4]

entries()

Returns the iterator of the index / value pair

var nums = [1,2,3,4];
const aEntries = Array.from(nums.entries()) //[[0, 1],[1, 2],[2, 3],[3, 4]]

Copy and fill method

fill()

Fill array

The fill function accepts three parameters: the data to be filled, the starting position of the filling (including this position), and the ending position of the filling (excluding this position).

var nums  = [1,1,1,1,1];
//Fill does not pass parameters. The default fill is undefined
nums.fill();//[undefined, undefined, undefined, undefined, undefined]
//Pass a parameter to fill all elements by default
nums.fill(1);//[1, 1, 1, 1, 1] reset

//Pass two parameters, and fill the position with index value greater than or equal to 2 to the end of the array with 2
nums.fill(2,2)//[1, 1, 2, 2, 2]
nums.fill(1);//[1, 1, 1, 1, 1] reset

//Pass three parameters, and fill 2 in the position where the index value is greater than or equal to 2 and less than 4
nums.fill(2,2,4) //[1, 1, 2, 2, 1]
nums.fill(1);//[1, 1, 1, 1, 1] reset

//When the second and third parameters have negative values, the final index value is negative + array length. The following index value is greater than or equal to 2 and less than 4, filled as 0,
nums.fill(0,-3,-1)//[1, 1, 0, 0, 1]
nums.fill(1);//[1, 1, 1, 1, 1] reset

//fill ignores the index range beyond the array boundary, 0 length and opposite direction by default
nums.fill(0,3,10) //[1, 1, 1, 0, 0]
nums.fill(1);//[1, 1, 1, 1, 1] reset
nums.fill(0,3,2) //[1, 1, 1, 1, 1] - opposite direction
nums.fill(5,7,10) //[1, 1, 1, 1] - out of bounds

copyWithin()

Batch copy
The copyWithin() function inserts the elements of the array within the specified range into the specified position. The inserted elements will cover the elements in the original position, and the length of the array will not change.

This function receives three parameters: the position of insertion, the position where the copy index starts, and the position where the copy index ends.

var arr = [0,1,2,3,4,5,6,7,8,9]

//When parameters are not passed, the default is unchanged
arr.copyWithin();//[0,1,2,3,4,5,6,7,8,9] 

//When passing a parameter, the parameter is the insertion position, the start position of the copy index is 0, and the end position is the end of the array
arr.copyWithin(5)//[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]

//When two parameters are passed, the first parameter is the insertion position, the second parameter is the start position of the copy index, and the end position is the end of the array
var arr = [0,1,2,3,4,5,6,7,8,9]//Reset
arr.copyWithin(5,2);//[0, 1, 2, 3, 4, 2, 3, 4, 5, 6]

//When three parameters are passed, the first parameter is the insertion position, the second parameter is the start position of the copy index, and the third parameter is the end position (excluding this position)

var arr = [0,1,2,3,4,5,6,7,8,9]//Reset
arr.copyWithin(5,2,5)//[0, 1, 2, 3, 4, 2, 3, 4, 8, 9]

Convert to string

toString() and toLocaleString() can convert arrays into strings

var arr = ['aa','bb','cc'];
arr.toString(); //"aa,bb,cc"
arr.toLocaleString(); //"aa,bb,cc"

The toString() method calls the toString() method on each element in the array, and then separates the results with commas
The toLocaleString() method calls the toLocaleString() method on each element in the array, and then separates the results with commas

Use the join method to replace the concatenated commas between array elements

var arr = ['aa','bb','cc'];
arr.join('|')//"aa|bb|cc"

join does not pass parameters. By default, it is separated by commas, which is the same as the result of calling toString()

arr.join()//"aa,bb,cc"

Stack method

Stack is a first in and last out data structure. If you want to operate the array as a stack structure, you can use push and pop functions. Both functions operate on the last bit of the array

pop()

pop pops up the last item of the array and returns it

var arr = ['aa','bb','cc'];
arr.pop() //Return 'cc'
console.log(arr) //["aa", "bb"]

push()

push pushes an element at the end of the array

var arr = ['aa','bb','cc'];
arr.push('ee') //Returns the current array length
console.log(arr)    //["aa", "bb", "cc", "ee"]

Queue method

Queue is a first in first out data structure. An array can also be simulated as a queue. The shift and unshift functions can be used to delete and add the array. Both functions operate on the first bit of the array

shift()

The shift function deletes the first element of the array and returns the value of the deleted element

var arr = ['aa','bb','cc'];
arr.shift(); //Return 'aa'
console.log(arr) //["bb", "cc"]

unshift()

The unshift function inserts an element in the first bit of the array, moves other elements one bit later, and returns the length of the current array

var arr = ['aa','bb','cc'];
arr.unshift('00')//4
console.log(arr) //["00", "aa", "bb", "cc"]

Sorting method

There are two ways to sort arrays: sort and reverse

reverse()

The reverse function simply reverses the array elements

var arr = ['b','c','d','e',34];
arr.reverse()//[34, "e", "d", "c", "b"]

sort()

The sort function receives a comparison function. You can customize the comparison rules, which is more flexible.
The sort function converts the array elements into strings and compares them

var arr = [0,2,5,3,19,10]
arr.sort((a,b)=>a<b?1:a>b?-1:0)
console.log(arr) //[19, 10, 5, 3, 2, 0]

Operation method

concat()

Array splicing method

var a1 = [1,2,3];
var a2 = a1.concat(4,[5,6,7]) //[1, 2, 3, 4, 5, 6, 7]

slice()

slice is used to create a new array containing one or more elements of the original array. (does not affect the original value)
Two parameters can be passed: the start position and end position of the intercepted index (intercepting elements that do not include the end position)

//When passing a parameter, the parameter is the start index position, which is intercepted to the end of the array by default
var arr = [1,2,3,4,5,6,7]
console.log(arr.slice(3))//[4, 5, 6, 7]
console.log(arr) //[1, 2, 3, 4, 5, 6, 7]

//When two parameters are passed, that is, the start and end positions of interception
console.log(arr.slice(2,5))//[3, 4, 5]

//If there is a negative value, the final index is the value plus the array length
console.log(arr.slice(-4,-1)) //[4, 5, 6]

splice()

The splice function can delete, insert and replace the array (it will act on the original array)

To delete, you need to specify two parameters: the index position at which the deletion starts and the number of deletes

var arr = [1,2,3,4,5,6,7]
arr.splice(1,2) //Delete the two elements starting with index 1, i.e. 2 and 3
console.log(arr) //[1, 4, 5, 6, 7]

Three parameters need to be passed for insertion: insertion position, 0 (number of deleted elements) and multiple inserted elements

var arr =[0,4,5];
arr.splice(1,0,1,2,3) //If you want to insert more than one element, add up after the third parameter, separated by commas
console.log(arr) //[0, 1, 2, 3, 4, 5]

Replace splice when deleting an element, you can insert a new element at the specified position. Similarly, you need to pass in three elements: the starting position, the number of deleted elements, and any replaced characters

var arr = [0,1,2,3,'a','b','c'];
arr.splice(4,3,4,5,6) //Start deleting three elements at the position with index 4, then insert three elements to complete the replacement, and return the deleted elements ["a", "b", "c"]
console.log(arr) //[0, 1, 2, 3, 4, 5, 6]

Search and location methods

Strict equality

indexOf(),lastIndexOf(),include() these three functions pass two parameters: the element to find and an optional starting position. In the process of comparison, the two must be strictly equal, that is, congruent (= = =) comparison is used

indexOf()

Search backward from the first item of the array. If found, return the index value. If not found, return - 1

var arr = [1,2,3,4,5,2,3,6];
arr.indexOf();//-1 

arr.indexOf(2) //1
//Find from index 3
arr.indexOf(2,3)//5
//If the initial index is negative, the final search index is negative plus the total length of the array, that is, the search starts from the index of 4
arr.indexOf(2,-3)//5

lastIndexOf()

Look forward from the last item of the array, find and return the index value, and return - 1 if not found

var arr = [1,2,3,4,5,2,3,6];
arr.lastIndexOf() //-1
//The default is to look forward from the last bit
arr.lastIndexOf(2)//5 
//Find forward from specified index 1
arr.lastIndexOf(2,1)//1

//When the starting search position is negative, it is still negative plus the total length of the array
arr.lastIndexOf(2,-4)//1

includes()

Search backward from the first item of the array. If it is found, it returns true. If it is not found, it returns false

var arr = [1,2,3,4,5,2,3,6];
arr.includes(2) //true

Assertion function

find() and findIndex() do not continue searching after finding a match
These two functions receive two parameters: the assertion function and an optional parameter object, which are used to specify the internal this value of the assertion function.
The assertion function accepts three parameters: the currently searched element, the index value of the current element, and the array being searched

var data = [
    {
        name:'zhangsan',
        age:28
    },
    {
        name: 'lisi',
        age:24
    }
]
const user = data.find((item,index,arr)=>item.age===28);
console.log(user)//{name: "zhangsan", age: 28}

const index = data.findIndex((item,index,arr)=>item.age===28);

console.log(index)//0

find returns the first matching element, and findIndex returns the index of the first matching element

var nums = [2,3,4,1,4];
nums.find((item,index,arr)=>{
    console.log(`item: ${item},  index:${index},  arr:${arr}`);
    return item === 4;
})
// item: 2,  index:0,  arr:2,3,4,1,4
// item: 3,  index:1,  arr:2,3,4,1,4
// item: 4,  index:2,  arr:2,3,4,1,4

Iterative method

every,filter,forEach,map,some
Each of the five iterative methods of the array receives two parameters: the function running with each item as the parameter and the optional scope object as the function running context (affecting the value of this in the function). The first function parameter receives three parameters: array element, element index and array itself.

every() and some()

every: each item of the array runs the incoming function. If each function returns true, this method returns true.
some: each item of the array runs the passed in function. If one item returns true, this method returns true.

var nums = [2, 3, 4, 1, 4];
var everyValue = nums.every((item,index,arr)=>item>2)//false
var someValue = nums.some((item,index,arr)=>item>2)//true

filter() and map()

filter(): run the passed in function for each item of the array. The items that return true will be combined into an array and returned.
map: run the passed in function for each item of the array and return an array composed of the results of each function call.

var nums = [2, 3, 4, 1, 4];
var filterResult = nums.filter((item,index,arr)=>item>2)//[3, 4, 4]

var mapResult = nums.map((item,index,arr)=>item*2)//[4, 6, 8, 2, 8] 

forEach()

forEach: run the passed in function for each item of the array without return value

var nums = [2, 3, 4, 1, 4];
nums.forEach((item,index,arr)=>{
    console.log(item)    //2 3 4 1 4
})

Merging method

Both the reduce and reduceright functions pass in two parameters: the function that each item will execute and the initial value of the optional merging starting point.
The first function parameter can pass four parameters: the previous merge value, the current item, the index value of the current item, and the array itself. The return value of the function is the merge value as the first parameter of the next function execution.

reduce()

The reduce method starts from the first item of the array and traverses to the last item.
If the function does not pass the second parameter (merge starting point value), the first iteration will start from the second item of the array, and then pass it to the merge function. The first parameter is the first item of the array, and the second parameter is the second item of the array.

var nums = [2, 3, 4, 1, 4];
//For the first time, pre is 2 and cur is 3 The second time the merge function is executed, pre is 5 (2 + 3), cur is 4 (the third item of the array), and the final merge value is returned after traversal
var sum = nums.reduce((pre,cur,index,arr)=>pre+cur);//14

reduceRight()

The reduceRight function starts from the last item of the array and traverses to the first item

var nums = [2, 3, 4, 1, 4];
var sum = nums.reduceRight((pre,cur,index,arr)=>pre+cur);//14

Topics: Javascript Front-end