Home  >  Article  >  Web Front-end  >  Summary and sharing of JavaScript array operation functions

Summary and sharing of JavaScript array operation functions

WBOY
WBOYforward
2022-07-04 13:47:431514browse

This article brings you relevant knowledge about javascript, which mainly organizes issues related to array operation functions, including element deletion, splice, slice, concat, etc. The following is Let's take a look, hope it helps everyone.

Summary and sharing of JavaScript array operation functions

[Related recommendations: javascript video tutorial, web front-end

Array advanced

The previous article 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, as mentioned above , this article will not go into details.

Element deletion (object method)

As 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 result is as follows:

Summary and sharing of JavaScript array operation functions

Pay attention to the yellow position in the picture, although the element has been deleted , but the length of the array is still 5, and there is an extra empty at the deleted position. If we access the element with the subscript 2, we will get the following result:

Summary and sharing of JavaScript array operation functions

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 in the array Yes, when we access the 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 the splice() method.

splice()

It should be noted in advance that the splice() method has quite a lot of functions. It is not just about deleting elements. The following is the syntax:

arr.splice(start[,deleteCount,e1,e2,...,eN])
The

splice method starts from the start position, deletes deleteCount elements, and then inserts e1, e2, e3 and other elements in place .

Delete an element

The following example can delete an element from the array:

let arr = [1,2,3,4,5]arr.splice(0,1);//删除掉第一个元素1console.log(arr)

The above code deletes the 1 at the first position in the array element, the execution result is as follows:

Summary and sharing of JavaScript array operation functions

Delete multiple elements

Deleting multiple elements is the same as deleting one element. You only need to change the second parameter. Just specify the number, for example:

let arr = [1,2,3,4,5];arr.splice(0,3);//删除前三个元素console.log(arr);//[4,5]

The code execution result is as follows:

Summary and sharing of JavaScript array operation functions

Truncate the array

If we only provide one Parameter start, then all elements after the position start of the array will be deleted. For example:

let arr = [1,2,3,4,5]arr.splice(2);//删除从下标为2以及后面的所有元素console.log(arr);//[1,2]

Code execution result:

Summary and sharing of JavaScript array operation functions

Element replacement

If we provide more than two parameters, then we can replace the 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 result is as follows:

Summary and sharing of JavaScript array operation functions

The above code actually performs a two-step operation, first deleting 2 elements starting from 0, and then at 0 Insert three new elements at the position.

Element insertion

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]

Summary and sharing of JavaScript array operation functions

Return value

splice()The 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 result:

Summary and sharing of JavaScript array operation functions

Negative index

We can use negative numbers to indicate the position of the element to start operating on, 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:

Summary and sharing of JavaScript array operation functions

slice()

slice()The method can intercept the array in the specified range, the syntax is as follows :

arr.slice([start],[end])

返回一个新数组,新数组从start开始,到end结束,但是不包括end

举例:

let arr = [1,2,3,4,5]console.log(arr.slice(2,5))//[3,4,5]console.log(arr.slice(1,3))//[2,3]

代码执行结果:

Summary and sharing of JavaScript array operation functions

slice()同样可以使用负数下标:

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]

代码执行结果如下:

Summary and sharing of JavaScript array operation functions

如果只为slice()方法提供一个参数,就会和splice()一样截断到数组末尾。

concat()

concat()函数可以将多个数组或者其他类型的值拼接称一个长数组,语法如下:

arr.concat(e1, e2, e3)

以上代码将返回一个新的数组,新数组由arr拼接e1e2e3而成。

举例:

let arr = [1,2,3]console.log(arr.concat([4,5],6,7,[8,9]))

代码执行结果如下:

Summary and sharing of JavaScript array operation functions

普通的对象,即使它们看起来和对象一样,仍然会被作为一个整体插入到数组中,例如:

let arr = [1,2]let obj = {1:'1',2:2}console.log(arr.concat(obj))

代码执行结果:

Summary and sharing of JavaScript array operation functions

但是,如果对象具有Symbol.isConcatSpreadable属性,就会被当作数组处理:

let arr = [1,2]let obj = {0:'x',
           1:'y',
           [Symbol.isConcatSpreadable]:true,
           length:2      }console.log(arr.concat(obj))

代码执行结果:

Summary and sharing of JavaScript array operation functions

forEach()

遍历整个数组,为每个数组元素提供一个操作函数,语法:

let arr = [1,2]arr.forEach((itm,idx,array)=>{
    ...})

应用举例:

let arr = [1,2,3,4,5]arr.forEach((itm)=>{
    console.log(itm)})

代码执行结果:

Summary and sharing of JavaScript array operation functions

let arr = [1,2,3,4,5]arr.forEach((itm,idx,array)=>{
    console.log(`arr[${idx}] in [${array}] is ${itm}`)})

代码执行结果:

Summary and sharing of JavaScript array operation functions

indexOf、lastIndexOf、includes

类似于字符串,indexOflastIndexOfincludes可与查询数组中指定元素的下标:

  1. arr.indexOf(itm,start):从start位置开始搜索itm,如果找到返回下标,否则返回-1;
  2. arr.lastIndexOf(itm,start):倒序查找整个数组,直至start处,返回第一个查到的下标(也就是数组最后一个匹配项),找不到返回-1;
  3. arr.includes(itm,start):从start位置开始搜索itm,找到返回true,否则返回false;

举例:

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

这些方法在比较数组元素的时候使用的是===,所以false0是不一样的。

NaN的处理

NaN是一个特殊的数字,三者在处理NaN有细微差别:

let arr = [NaN,1,2,3,NaN]console.log(arr.includes(NaN))//trueconsole.log(arr.indexOf(NaN))//-1console.log(arr.lastIndexOf(NaN))//-1

产生这种结果的原因和NaN本身的特性有关,即NaN不等于任何数字,包括他自己。

这些内容在前面的章节已经讲过了,遗忘的童鞋记得温故知新呀。

find、findIndex

在编程过程中常常会遇到对象数组,而对象是不能直接使用===比较的,如何从数组中查找到满足条件的对象呢?

这个时候就要使用findfindIndex方法,语法如下:

let result = arr.find(function(itm,idx,array){
    //itm数组元素
    //idx元素下标
    //array数组本身
    //传入一个判断函数,如果该函数返回true,就返回当前对象itm})

举个栗子,我们查找name属性等于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)

代码执行结果:

Summary and sharing of JavaScript array operation functions

如果没有符合条件的对象,就会返回undefined

以上代码还可以简化为:

let xiaoming = arr.find((itm)=> itm.name == 'xiaoming')

执行效果是完全相同的。

arr.findIndex(func)的用途和arr.find(func)几乎相同,唯一不同的地方在于,arr.findIndex返回符合条件对象的下标而不对象本身,找不到返回-1

filter

findfindIndex只能查找一个满足要求的对象,如果一个数组中存在多个满足要求的对象,就需要使用filter方法,语法如下:

let results = arr.filter(function(itm,idx,array){
    //和find的用法相同,不过会返回符合要求的对象数组
    //找不到返回空数组})

举个例子:

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)

代码执行结果:

Summary and sharing of JavaScript array operation functions

map

arr.map方法可以对数组的每个对象都调用一个函数,然后返回处理后的数组,这是数组最有用的、最重要的方法之一。

语法:

let arrNew = arr.map(function(itm,idx,array){
    //返回新的结果})

举例,返回字符串数组对应的长度数组:

let arr = ['I','am','a','student']let arrNew = arr.map((itm)=>itm.length)//return itm.lengthconsole.log(arrNew)//[1,2,1,7]

代码执行结果:

Summary and sharing of JavaScript array operation functions

sort

arr.sort对数组进行原地排序,并返回排序后的数组,但是,由于原数组已经发生了改变,返回值实际上没有什么意义。

所谓原地排序,就是在原数组空间内排序,而不是新建一个数组

let arr = ['a','c','b']arr.sort()console.log(arr)

代码执行结果:

Summary and sharing of JavaScript array operation functions

注意,默认情况下sort方法是以字母序进行排序的,也就是适用于字符串排序,如果要排列其他类型的数组,需要自定义比较方法

数字数组

let arr = [1,3,2]arr.sort(function(a,b){
    if(a > b)return 1;
    if(a <p>代码执行结果:</p><p><img src="https://img.php.cn/upload/article/000/000/067/cc3e9c8ac4f7ab0bca3cb1f3f71220d5-22.png" alt="Summary and sharing of JavaScript array operation functions"></p><p><code>sort</code>函数内部采用了快速排序算法,也可能是<code>timsort</code>算法,但是这些我们都不需要关心,我们只需要关注比较函数就可以了。</p><p>比较函数可以返回任何数值,正数表示<code>></code>,负数表示<code>,<code>0</code>表示等于,所以我们可以简化数字比较方法:</code></p><pre class="brush:php;toolbar:false">let arr = [1,3,2]arr.sort((a,b)=> a - b)

如果想要逆序排列只需要交换一下ab的位置既可以了:

let arr = [1,3,2]arr.sort((a,b)=> b - a)

字符串排序

别忘了字符串比较要使用str.localeCompare(str1)方法呦

let arr = ['asdfas','success','failures']arr.sort((a,b)=>a.localeCompare(b))

代码执行结果:

Summary and sharing of JavaScript array operation functions

reverse

arr.reverse用于逆序数组

let arr = [1,2,3]arr.reverse()console.log(arr)//[3,2,1]

这个没啥好说的。

str.split()和arr.join()

还记得字符串分割函数吗?字符串分割函数可以将字符串分割成一个字符数组:

let str = 'xiaoming,xiaohong,xiaoli'let arr = str.split(',')//['xiaoming','xiaohong','xiali']

冷门知识,split函数有第二个参数,可以限制生成数组的长度

let str = 'xiaoming,xiaohong,xiaoli'let arr = str.split(',',2)//['xiaoming','xiaohong']

arr.join()方法用途和split方法相反,可以将一个数组组合成一个字符串。

举个栗子:

let arr = [1,2,3]let str = arr.join(';')console.log(str)

代码执行结果:

Summary and sharing of JavaScript array operation functions

reduce、reduceRight

arr.reduce方法和arr.map方法类似,都是传入一个方法,然后依次对数组元素调用这个方法,不同的地方在于,app.map方法在处理数组元素时,每次元素调用都是独立的,而arr.reduce会把上一个元素的调用结果传到当前元素处理方法中。

语法:

let res = arr.reduce(function(prev,itm,idx,array){
    //prev是上一个元素调用返回的结果
    //init会在第一个元素执行时充当上一个元素调用结果},[init])

试想一下,如何实现一个数字组成的数组元素和呢?map是没有办法实现的,这个时候就需要使用arr.reduce

let arr = [1,2,3,4,5]let res = arr.reduce((sum,itm)=>sum+itm,0)console.log(res)//15

代码执行过程如下图:

Summary and sharing of JavaScript array operation functions

arr.reduceRightarr.reduce用途相同,只不过从右往左对元素调用方法。

Array.isArray()

数组是对象的一种特例,使用typeof无法准确的分辨二者的区别:

console.log(typeof {})//objectconsole.log(typeof [])//object

二者都是对象,我们需要使用Array.isArray()方法进一步做判断:

console.log(Array.isArray({}))//falseconsole.log(Array.isArray([]))//true

some、every

arr.some(func)arr.every(func)方法用于检查数字,执行机制和map类似。

some

对每个数组元素执行传入的方法,如果方法返回true,立即返回true,如果所有的元素都不返回true,就返回false

every

对数组的每个元素执行传入的方法,如果所有元素都返回true,则返回true,否则返回false

举个例子:

let arr = [1,2,3,4,5]//判断数组是否存在大于2的元素console.log(arr.some((itm)=>{
    if(itm > 2)return true;}))//true//判断是否所有的元素都大于2console.log(arr.every((itm)=>{
    if(itm > 2)return true;}))//false

thisArg

在所有的数组方法中,除了sort,都有一个不常用固定参数thisArg,语法如下:

arr.find(func,thisArg)arr.filter(func,thisArg)arr.map(func,thisArg)

如果我们传入了thisArg,那么它就会在func中变为this

这个参数在常规情况下是没什么用处的,但是如果func是一个成员方法(对象的方法),而且方法中使用了this那么thisArg就会非常有意义。

举个例子:

let obj = {
    num : 3,
    func(itm){
        console.log(this)
        return itm > this.num;//查找大于3的数字
    }}let arr = [1,2,3,4,5,6,7]let newArr = arr.filter(obj.func,obj)console.log(newArr)

代码执行结果:

Summary and sharing of JavaScript array operation functions

这里我们可以看到,func中输出的this就是我们传入的thisArg值。

如果我们使用对象成员方法,同时不指定thisArg的值,就会造成thisundefined,从而导致程序错误。

【相关推荐:javascript视频教程web前端

The above is the detailed content of Summary and sharing of JavaScript array operation functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete