introduced the basic concepts of arrays and some simple array element operation functions. In fact, arrays provide many more functions.
push
, pop
, shift
and unshift
are functions that operate on both ends of the array. They have been mentioned above and will not be repeated in this article.
has been briefly introduced in the previous article. An array is a special object, so we can try to use the object's attribute deletion method: delete
.
For example:
let arr = [1,2,3,4,5];delete arr[2];console.log(arr);
The code execution results are as follows:
Pay attention to the yellow position in the picture. Although the element has been deleted, the length of the array is still 5
, and there is an extra空
in the deleted position. If we access the element with index 2
, we will get the following result:
The reason for this phenomenon is that delete obj.key
removes the corresponding value through key
, that is to say, delete arr[2]
deletes the 2:3
key-value pair in the array. When we access subscript 2
, it is undefined
.
In an array, we often hope that after deleting an element, the position of the element will be filled by subsequent elements and the length of the array will become shorter.
At this time, we need splice()
method.
needs to be noted in advance that splice()
method is quite versatile and does not only delete elements. The following is the syntax:
arr.splice(start[,deleteCount,e1,e2,...,eN])
splice
method Starting from the start
position, delete deleteCount
elements, and then insert e1,e2,e3
and other elements in place.
The following example can delete an element from the array:
let arr = [1,2,3,4,5]arr.splice(0,1);//Delete the first element 1console.log(arr)
The above code deletes 1
element at the first position in the array. The execution results are as follows:
is the same as deleting one element. You only need to change the second parameter to the specified number. For example:
let arr = [1,2,3,4,5];arr. splice(0,3);//Delete the first three elements console.log(arr);//[4,5]
The code execution results are as follows:
If we only provide one parameter start
, then all elements after start
position of the array will be deleted. For example:
let arr = [1,2,3,4,5]arr.splice(2);//DeleteConsole.log(arr);//[1,2]
code execution results
from subscript 2 and all subsequent elements:
If we provide more than two parameters, we can replace array elements, for example:
let arr = [1,2,3,4,5];arr.splice(0,2,'itm1',' itm2','itm3');console.log(arr);//['itm1','itm2','itm3',3,4,5]
The code execution results are as follows:
The above code actually performs a two-step operation, first deleting 2
elements starting from 0
, and then inserting three new elements at position 0
.
If we change the second parameter (the number of deletions) to 0
, then we can only insert elements without deleting elements. For example:
let arr = [1,2,3,4,5]arr.splice( 0,0,'x','y','z')console.log(arr);//['x','y','z'1,2,3,4,5]
The splice()
function will return the deleted element array, for example:
let arr = [1,2,3,4,5]let res = arr.splice(0,3,'x','y' )console.log(arr)//['x','y',4,5]console.log(res)//[1,2,3]
Code execution results:
We can use negative numbers to indicate the position where to start operating elements, for example:
let arr = [1,2,3,4,5]arr.splice(-1,1,'x','y','z ')console.log(arr)//[1,2,3,4,'x','y','z']
The code execution results are as follows:
slice()
method can intercept an array in a specified range. The syntax is as follows:
arr.slice([start],[end])
returns a new array. The new array starts from start
and ends at end
, but does not include end
.
Example:
let arr = [1,2,3,4,5]console.log(arr.slice(2,5))//[3,4,5]console.log(arr.slice(1,3) )//[2,3]
Code execution result:
slice()
can also use negative subscripts:
let arr = [1,2,3,4,5]console.log(arr.slice(-3))//[3,4,5]console.log(arr .slice(-5,-1))//[1,2,3,4]
The code execution results are as follows:
If you provide only one parameter to the slice()
method, it will be truncated to the end of the array just like splice()
.
The concat()
function can concatenate multiple arrays or other types of values into a long array. The syntax is as follows:
arr.concat(e1, e2, e3)
The above code will return a new array, and the new array is concatenated by arr
It is formed by e1
, e2
and e3
.
Example:
let arr = [1,2,3]console.log(arr.concat([4,5],6,7,[8,9]))
The code execution result is as follows:
Ordinary objects, even if they look the same as objects, are still inserted into the array as a whole, for example:
let arr = [1,2]let obj = {1:'1',2:2}console.log (arr.concat(obj))
code execution results:
However, if the object has the Symbol.isConcatSpreadable
property, it will be treated as an array:
let arr = [1,2]let obj = {0:'x', 1:'y', [Symbol.isConcatSpreadable]:true, length:2 }console.log(arr.concat(obj))
code execution results:
traverses the entire array and provides an operation function for each array element. Syntax:
let arr = [1,2]arr.forEach((itm,idx,array)=>{ ...})
Application example:
let arr = [1,2,3,4,5]arr.forEach((itm)=>{ console.log(itm)})
code execution results:
let arr = [1,2,3,4,5]arr.forEach((itm,idx,array)=>{ console.log(`arr[${idx}] in [${array}] is ${itm}`)})
code execution results:
are similar to strings. indexOf
, lastIndexOf
, and includes
can be used with the subscript of the specified element in the query array:
arr.indexOf(itm,start)
: Search for itm
starting from start
position. If found, return the subscript, otherwise return -1
;arr.lastIndexOf(itm,start)
: Search the entire array in reverse order until start
, and return the first found subscript (that is, the last matching item in the array). If not found, return -1
;arr.includes(itm,start)
: Search for itm
from start
position, return true
if found, otherwise return false
;example:
let arr = [1,2,3,4,5,6,"7","8","9" ,0,0,true,false]console.log(arr.indexOf(0))//9console.log(arr.lastIndexOf(0))//10console.log(arr.includes(10))//falseconsole. log(arr.includes(9))//false
These methods use ===
when comparing array elements, so false
and 0
are different.
Handling of NaN
NaN
is a special number, and there are subtle differences between the three in handling NaN
:
let arr = [NaN,1,2,3,NaN]console.log(arr.includes(NaN))//trueconsole.log( arr.indexOf(NaN))//-1console.log(arr.lastIndexOf(NaN))//-1The
reason for this result is related to the characteristics of NaN
itself, that is, NaN
is not equal to any number, including himself.
These contents have been discussed in the previous chapters. For forgotten children’s shoes, remember to review the past and learn the new.
often encounter object arrays during the programming process, and objects cannot be directly compared using ===
. How to find objects that meet the conditions from the array?
At this time, you need to use find
and findIndex
methods. The syntax is as follows:
let result = arr.find(function(itm,idx,array){ //itm array element //idx element subscript //array array itself //pass in a judgment function, if the function returns true, return the current object itm})
For example, we look for objects whose name
attribute is equal to xiaoming
:
let arr =[ {id:1,name:'xiaoming'}, {id:2,name:'xiaohong'}, {id:3,name:'xiaojunn'},]let xiaoming = arr.find(function(itm,idx,array){ if(itm.name == 'xiaoming')return true;})console.log(xiaoming)
code execution result:
If there is no object that meets the conditions, undefined
will be returned.
The above code can also be simplified to:
let xiaoming = arr.find((itm)=> itm.name == 'xiaoming').
The execution effect is exactly the same.
The purpose of arr.findIndex(func)
is almost the same as arr.find(func)
The only difference is that arr.findIndex
returns the subscript of the qualified object instead of the object itself. If it is not found, it returns -1
.
find
and findIndex
can only find one object that meets the requirements. If there are multiple objects that meet the requirements in an array, you need to use filter
method. The syntax is as follows:
let results = arr.filter(function(itm,idx,array){ //Same usage as find, but will return an array of objects that meet the requirements //If not found, an empty array will be returned})
For example:
let arr =[ {id:1,name:'xiaoming'}, {id:2,name:'xiaohong'}, {id:3,name:'xiaojunn'},]let res = arr.filter(function(itm,idx,array){ if(itm.name == 'xiaoming' || itm.name == 'xiaohong')return true;})console.log(res)
code execution result:
Thearr.map
method can call a function on each object of the array and then return the processed array. This is one of the most useful and important methods of arrays.
Syntax:
let arrNew = arr.map(function(itm,idx,array){ //Return new result})
For example, return the length array corresponding to the string array:
let arr = ['I','am','a','student']let arrNew = arr.map((itm)= >itm.length)//return itm.lengthconsole.log(arrNew)//[1,2,1,7]
code execution result:
arr.sort
sorts the array in place and returns the sorted array. However, since the original array has been changed, the return value is actually meaningless.
The so-called in-place sorting means sorting within the original array space instead of creating a new array
let arr = ['a','c','b']arr.sort()console.log(arr)
code execution result:
Note that by default, the
sort
method sorts in alphabetical order , which is suitable for string sorting. If you want to sort other types of arrays, you need to customize the comparison method
for numeric arrays
let arr = [1,3,2]arr. sort(function(a,b){ if(a > b)return 1; if(a < b)return -1; return 0;})
Code execution result:
sort
function uses the quick sort algorithm internally, or it may be the timsort
algorithm, but we don't need to care about these, we only need to pay attention to the comparison function.
The comparison function can return any numerical value, a positive number means >
, a negative number means <
, and 0
means equal, so we can simplify the numerical comparison method:
let arr = [1,3,2]arr.sort((a,b)=> a - b)
If you want to sort in reverse order, just swap the positions of a
and b
:
let arr = [1,3,2]arr.sort((a,b)=> b - a)
String
sorting Forgot to use str.localeCompare(str1)
method for string comparison?
let arr = ['asdfas','success','failures']arr.sort((a,b)=>a.localeCompare(b))
code Execution result:
arr.reverse
is used for reverse arrays
let arr = [1,2,3]arr.reverse()console.log(arr)//[3,2,1]
There is nothing to say about this.
Remember the string splitting function? The string splitting function can split the string into a character array:
let str = 'xiaoming,xiaohong,xiaoli'let arr = str.split(',')//['xiaoming','xiaohong','xiali']
Unpopular knowledge, the
split
function has a second parameter, which can limit the length of the generated arraylet str = 'xiaoming,xiaohong,xiaoli'let arr = str.split(',',2)//['xiaoming','xiaohong' ]
The arr.join()
method is the opposite of the split
method. It can combine an array into a string.
For example:
let arr = [1,2,3]let str = arr.join(';')console.log(str)
code execution result:
arr.reduce
method is similar to the arr.map
method. They both pass in a method and then call this method on the array elements in sequence. The difference is that when app.map
method processes array elements, each element call is independent, and arr.reduce
will pass the call result of the previous element to the current element processing method.
Syntax:
let res = arr.reduce(function(prev,itm,idx,array){ //prev is the result returned by the previous element call //init will serve as the result of the previous element call when the first element is executed}, [init])
Just imagine, how to implement the sum of array elements composed of numbers? There is no way to implement map. At this time, you need to use arr.reduce
:
let arr = [1,2,3,4,5]let res = arr.reduce((sum,itm)=>sum+itm,0) console.log(res)//15
The code execution process is as follows:
arr.reduceRight
has the same purpose as arr.reduce
, except that methods are called on elements from right to left.
Array is a special case of object. Using typeof
cannot accurately distinguish the difference between the two:
console.log(typeof {})//objectconsole.log(typeof [])//object
Both are objects , we need to use Array.isArray()
method to make further judgments:
console.log(Array.isArray({}))//falseconsole.log(Array.isArray([]))//true
arr.some(func)
and arr.every(func)
methods are used to check numbers, and the execution mechanism is similar to map
.
some
executes the passed method on each array element. If the method returns true
, it returns true
immediately. If all elements do not return true
, it returns false
.
every
executes the passed-in method on each element of the array, returning true
if all elements return true
, otherwise it returns false
.
For example:
let arr = [1,2,3,4,5]//Determine whether there are elements greater than 2 in the array console.log(arr.some((itm)=>{ if(itm > 2)return true;}))//true//Determine whether all elements are greater than 2console.log(arr.every((itm)=>{ if(itm > 2)return true;}))//false
In all array methods, except sort
, there is an uncommon fixed parameter thisArg
. The syntax is as follows:
arr.find(func,thisArg)arr.filter( func,thisArg)arr.map(func,thisArg)
If we pass in thisArg
, then it will become this
in func
.
This parameter is of little use under normal circumstances, but if func
is a member method (method of an object), and this
is used in the method, then thisArg
will be very meaningful.
For example:
let obj = { num: 3, func(itm){ console.log(this) return itm > this.num;//Find numbers greater than 3}}let arr = [1,2,3,4,5,6,7]let newArr = arr.filter(obj.func,obj)console.log (newArr)
code execution result:
Here we can see that this
output in func
is the thisArg
value we passed in.
If we use object member methods without specifying the value of thisArg
, this
will be undefined
, resulting in a program error.