关于javascript:爆-肝-一-周-总-结-最全-JavaScript-Array-方法详解

4次阅读

共计 11923 个字符,预计需要花费 30 分钟才能阅读完成。

前言

咱们在日常开发中,与接口打交道最多了,前端通过拜访后端接口,而后将接口数据二次解决渲染到页面当中。

二次解决的过程是 考验 CoderArray 是否纯熟 以及 在 何种 场景下应用哪种办法解决最优。

小编,在最近开发中就遇到了 Array 问题,在解决简单的业务需要时,没想到Array 有相似的办法,而后将办法 组合起来解决当下问题。

文章用下班时间肝了一周才写完,看完点赞、转发 是对我最大的反对。


遍历数组办法

不会扭转原数组的遍历办法

forEach()

forEach() 办法依照升序为数组中每一项执行一次给定的函数。

语法

arr.forEach(callback(currentValue , index , array),thisArg)
  • currentValue : 数组以后项值
  • index : 数组以后项索引
  • arr : 数组对象自身
  • thisArg : 可选参数。当执行回调函数 callback 时,用作 this 的值。

留神

  • 如果应用 箭头函数表达式 来传入函数参数,thisArg 参数会被疏忽,因为箭头函数在词法上绑定了 this 值。
  • forEach 不会间接扭转调用它的对象,然而那个对象可能会被 callback 函数扭转。
  • every 不会扭转原数组。
// 防盗贴:微信公众号: 前端自学社区

const arr = [2,3,4,1,44]

arr.forEach(val =>{console.log(` 值为 ${val*2}`)
    
})
console.log(` 原数组为 ${arr}`);
// 值为 4
// 值为 6
// 值为 8
// 值为 2
// 值为 88
// 原数组为 2,3,4,1,44

reduce()

reduce()数组元素累计器,返回一个合并的后果值。

语法

arr.reduce(callback(accumulator, currentValue, index, array), initialValue)
  • accumulator : 累计器,默认为数组元素第一个值
  • currentValue : 以后值
  • index : 以后元素索引 <font style=”color:red”> 可选 </font>
  • array : 数组 <font style=”color:red”> 可选 </font>
  • initialValue : 初始值 <font style=”color:red”> 可选 </font>

reduce 有两个参数,一个是回调函数,一个是初始值。

它有两种取值状况:

    1. 当提供了 initialValue 初始值时,那么 accumulator 的值为 initialValue , currentValue 的值为 数组第一个值
    1. 当没有提供 initialValue 初始值时,那么 accumulator 的值 为 数组第一个值,currentValue 为第二个值。

留神

  • 如果数组为空,且没有提供initialValue 初始值时,会抛出 TypeError .
  • 如果数组有一个元素,且没有提供initialValue 或者 提供了initialValue,数组为空,那么惟一值被返回不会执行 callback 回调函数。

求和

// 防盗贴:微信公众号: 前端自学社区 /
const arr = [1, 2, 3, 4]

const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 10)

console.log(sum) //20 
// accumulator  累计器
// currentValue  以后值
// initialValue  累计 初始值 为 10 

//10 + 1 + 2 + 3 + 4


## 留神
// 回调函数第一次执行时,accumulator 和 currentValue 的取值有两种状况:// 如果调用 reduce()时提供了 initialValue,accumulator 取值为 initialValue,currentValue 取数组中的第一个值;// 如果没有提供 initialValue,那么 accumulator 取数组中的第一个值,currentValue 取数组中的第二个值。

计算对象中的值

要累加对象数组中蕴含的值,必须提供初始值,以便各个 item 正确通过你的函数。

/*
 * @Description: 
 * @Author: 微信公众号: 前端自学社区
 * @Date: 2021-08-07 00:53:51
 * @LastEditTime: 2021-08-07 00:53:51
 * @LastEditors: Do not edit
 */
const data = [
    {
        date: '2021-8-1',
        income: 200
    },
    {
        date: '2021-8-2',
        income: 400
    },
    {
        date: '2021-8-3',
        income: 300
    },
]

console.log(` 总收入:${data.reduce( (pre,currentValue) => pre + currentValue.income,0)}`);
// 总收入:900

二维数组转一位数组

const array = [[1,2],[3,4]]

console.log(array.reduce((a,b) => a.concat(b)));
//[1, 2, 3, 4]

find()

find() 返回满足特定条件的元素对象或者元素值,不满足返回 undefined

语法

arr.find((element,index,array), thisArg)
  • element:以后元素
  • index : 以后元素索引 <font style=”color:red”> 可选 </font>
  • array : 数组自身 <font style=”color:red”> 可选 </font>
  • thisArg : 执行回调时用作this 的对象。<font style=”color:red”> 可选 </font>
// 从数据中找出第一个满足特定条件的对象

const data = [
    {
        name:'张三',
        article: 3
    },
    {
        name:'老王',
        article: 9
    },
    {
        name:'老李',
        article: 10
    }
]

console.log(data.find(item => item.article > 9));

// {name: '老李', article: 10}

findIndex()

findIndex() 返回数组中符合条件的第一个元素的索引,没有,则返回 -1

语法

arr.findIndex((element,index,array), thisArg)
  • element:以后元素
  • index : 以后元素索引 <font style=”color:red”> 可选 </font>
  • array : 数组自身 <font style=”color:red”> 可选 </font>
  • thisArg : 执行回调时用作this 的对象。<font style=”color:red”> 可选 </font>
const arr = [22,33,44,55]
console.log(arr.findIndex(val => val > 33));    //2
console.log(arr.findIndex(val => val > 99));    //-1

key()

key() 返回一个新的 Array Iterator 对象,该对象蕴含数组中每个索引的键。

语法

keys()

留神

  • 如果数组中有空原元素,在获取 key 时,也会退出遍历的队列中。
const inputModal = [
    {name:''},
    {age:''},
    {hobby:''}
]
for(const key of inputModal.keys()){console.log(key)
}
// 0
// 1
// 2

const arr = [1,2,,3]
for(const key of arr.keys()){console.log(key);
}
// 0
// 1
// 2
// 3


//Object.keys() 办法会返回一个由一个给定对象的本身可枚举属性组成的数组
// 所以 Object.keys(arr) = ['0', '1', '3']
for(const key of Object.keys(arr)){console.log(key);
}
// 0
// 1
// 3

values()

values() 办法返回一个新的 Array Iterator 对象,该对象蕴含数组每个索引的值。

语法

arr.values()
const Color = ['red','yelloe','orange']

for(val of Color.values()){console.log(val);
}
// red
// yelloe
// orange

<hr/>

返回 布尔值

every()

every 用来判断数组内所有元素是否合乎某个条件,返回 布尔值

语法

arr.every(callback(currentValue , index , array),thisArg)
  • currentValue : 数组以后项值 <font style=”color:red”> 必须 </font>
  • index : 数组以后项索引 <font style=”color:red”> 可选 </font>
  • arr : 数组对象自身 <font style=”color:red”> 可选 </font>
  • thisArg : 可选参数。当执行回调函数 callback 时,用作 this 的值。<font style=”color:red”> 可选 </font>

留神

  • 当所有的元素都符合条件才会返回true
  • every 不会扭转原数组。
  • 若传入一个空数组,无论如何都会返回 true
// 防盗贴:微信公众号: 前端自学社区

const arr = [2,3,4,1,44]

console.log(arr.every(val =>  val > 0));   //true

console.log(arr.every(val => { val > 2})) //false

some()

some() 用来判断数组元素是否合乎某个条件,只有有一个元素合乎,那么返回 true.

语法

arr.some(callback(currentValue , index , array),thisArg)
  • currentValue : 数组以后项值 <font style=”color:red”> 必须 </font>
  • index : 数组以后项索引 <font style=”color:red”> 可选 </font>
  • arr : 数组对象自身 <font style=”color:red”> 可选 </font>
  • thisArg : 可选参数。当执行回调函数 callback 时,用作 this 的值。<font style=”color:red”> 可选 </font>

留神

  • some() 被调用时不会扭转数组。
  • 如果用一个空数组进行测试,在任何状况下它返回的都是false
  • some() 在遍历时,元素范畴曾经确定,在遍历过程中增加的元素,不会退出到遍历的序列中。
const arr = [2,3,4,1,44]

console.log(arr.some(val => val > 2))  //true
console.log([].some(val => val > 2)); //false


const newList = [11,22,33,44]
console.log(newList.some(val => {newList.push(55)
    newList.push(66)
    val > 55
}));   //false

不扭转原有数组,造成新的数组

filter()

filter() 用来遍历原数组,过滤拿到符合条件的数组元素,造成新的数组元素。

语法

arr.some(callback(currentValue , index , array),thisArg)
  • currentValue : 数组以后项值 <font style=”color:red”> 必须 </font>
  • index : 数组以后项索引 <font style=”color:red”> 可选 </font>
  • arr : 数组对象自身 <font style=”color:red”> 可选 </font>
  • thisArg : 可选参数。当执行回调函数 callback 时,用作 this 的值。<font style=”color:red”> 可选 </font>

留神

  • filter 不会扭转原数组,它返回过滤后的新数组。
  • filter() 在遍历时,元素范畴曾经确定,在遍历过程中增加的元素,不会退出到遍历的序列中。
const arr = [11,22,33,44,55,66]
 

console.log(arr.filter(val => val > 44))
console.log(` 原数组为 ${arr}`);

// [55, 66]
// 原数组为 11,22,33,44,55,66

map()

map() 创立一个新的数组,其后果是该数组中的每个元素都调用一个提供的函数后返回的后果。

语法

arr.map(callback(currentValue , index , array),thisArg)
  • currentValue : 数组以后项值 <font style=”color:red”> 必须 </font>
  • index : 数组以后项索引 <font style=”color:red”> 可选 </font>
  • arr : 数组对象自身 <font style=”color:red”> 可选 </font>
  • thisArg : 可选参数。当执行回调函数 callback 时,用作 this 的值。<font style=”color:red”> 可选 </font>

留神

  • map 不批改调用它的原数组自身
  • map() 在遍历时,元素范畴曾经确定,在遍历过程中增加的元素,不会退出到遍历的序列中。
const arr = [1,2,3,4]

console.log(arr.map(val => val*3))  // [3, 6, 9, 12]
console.log(arr)  // [1, 2, 3, 4]

<hr/>

数组 CRUD

扭转原数组办法

reverse()

reverse() 办法将数组中元素的地位颠倒,并返回该数组。数组的第一个元素会变成最初一个,数组的最初一个元素变成第一个。该办法会扭转原数组。

const arr = [1,2,3]

console.log(arr.reverse(11,22,33))  //[3, 2, 1]

sort()

sort() 办法采纳 原地算法 进行排序并返回数组。默认排序程序是在 将元素转换为字符串 ,而后 比拟它们的 UTF-16 代码单元值序列

原地算法 是一个应用辅助的数据结构对输出进行转换的算法。然而,它容许有大量额定的存储空间来贮存辅助变量。当算法运行时,输出通常会被输入笼罩。原地算法仅通过替换或替换元素来更新输出序列。

const arr = [23,11,33,44,1]

console.log(arr.sort())  //[1, 11, 23, 33, 44]


const arr = [23,11,33,44,1000000000]

console.log(arr.sort())  
// [1000000000, 11, 23, 33, 44]

删除元素

shift()

shift() 办法从数组中删除 第一个 元素,并返回该元素的值。此办法更改数组的长度。

语法

arr.shift()

留神

  • 从数组中删除的元素; 如果数组为空则返回undefined
const data = [
    {
        id:1,
        name:'前端'
    },
    {
        id:2,
        name:'后端'
    },
    {
        id:3,
        name:'挪动端'
    },
    {
        id:4,
        name:'嵌入式开发'
    },
]

const deleObj = data.shift()



console.log('============== 删除后的元素 ======================');
console.log(data);
console.log('================= 删除后的元素 ===================');


console.log('=============== 被删除的元素 =====================');
console.log(deleObj);
console.log('================ 被删除的元素 ====================');

//  ============== 删除后的元素 ======================
// [//     { id: 2, name: '后端'},
//     {id: 3, name: '挪动端'},
//     {id: 4, name: '嵌入式开发'}
//   ]
//   ================= 删除后的元素 ===================

  
//   =============== 被删除的元素 =====================
//   {id: 1, name: '前端'}
//   ================ 被删除的元素 ====================

pop()

pop()办法从数组中删除最初一个元素,并返回该元素的值。此办法更改数组的长度。

用法和 shift 相似。

语法

arr.pop()

留神

  • 从数组中删除的元素; 如果数组为空则返回undefined
const data = [
    {
        id:1,
        name:'前端'
    },
    {
        id:2,
        name:'后端'
    },
    {
        id:3,
        name:'挪动端'
    },
    {
        id:4,
        name:'嵌入式开发'
    },
]

const deleObj = data.pop()




console.log(data);
// [//     { id: 1, name: '前端'},
//     {id: 2, name: '后端'},
//     {id: 3, name: '挪动端'}
// ]
console.log(deleObj);
// {id: 4, name: '嵌入式开发'}

splice()

splice() 办法通过 删除 替换 现有元素或者原地增加新的元素来批改数组, 并以数组模式返回被批改的内容。此办法会扭转原数组。

语法

array.splice(start,deleteCount, [item1,item2....])
  • start : 开始的索引
  • deleteCount : 删除的个数 <font style=”color:red”> 可选 </font>
  • [item1,item2 .....];从开始的索引进行 增加的减少和替换的元素,<font style=”color:red”> 可选 </font>

留神

  • 由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只蕴含一个元素的数组。如果没有删除元素,则返回空数组。
  • 如果只传递了开始的索引地位,则会删除索引后的所有元素对象

    const data = [
        {
            id:1,
            name:'前端'
        },
        {
            id:2,
            name:'后端'
        },
        {
            id:3,
            name:'挪动端'
        },
        {
            id:4,
            name:'嵌入式开发'
        },
    ]
    data.splice(1)
    console.log(data)
    // [{ id: 1, name: '前端'} ]
    

从索引为 2 开始,删除 1 个数组元素对象,增加两个数组元素对象

const data = [
    {
        id:1,
        name:'前端'
    },
    {
        id:2,
        name:'后端'
    },
    {
        id:3,
        name:'挪动端'
    },
    {
        id:4,
        name:'嵌入式开发'
    },
]


data.splice(2,1,...[{id:5,name:'人工智能'},{id:6,name:'大数据开发'}])

console.log(data);
// [//     { id: 1, name: '前端'},
//     {id: 2, name: '后端'},
//     {id: 5, name: '人工智能'},
//     {id: 6, name: '大数据开发'},
//     {id: 4, name: '嵌入式开发'}
// ]

减少元素

splice()

下面曾经有介绍

push()

push() 办法将一个或多个元素增加到数组的 开端,并返回该数组的新长度。

语法

arr.push(element1, ..., elementN)
const data = [
    {
        id:1,
        name:'前端'
    },
    {
        id:2,
        name:'后端'
    },
]

console.log(data.push({id:3,name:'挪动端'}))  //3

合并数组

const data = [
    {
        id:1,
        name:'前端'
    },
    {
        id:2,
        name:'后端'
    },
]


var obj = [
    {
        id:4,
        name:'嵌入式开发'
    },
]

// 相当于 data.push({id:4,name:'嵌入式开发'});
Array.prototype.push.apply(data, obj);

console.log(data);

[{ id: 1, name: '前端'},
  {id: 2, name: '后端'},
  {id: 4, name: '嵌入式开发'}
]

unshift()

unshift() 办法将一个或多个元素增加到数组的 结尾 ,并返回该数组的 新长度

const arr = [1,2,3]



console.log(arr.unshift(11,22,33))  //6 
console.log(arr)  //[11, 22, 33, 1, 2, 3]

不扭转原数组元素办法

indexOf()

indexOf()办法返回能够在数组中找到给定元素的第一个索引,如果不存在,则返回 -1。

语法

indexOf(searchElement)
indexOf(searchElement, fromIndex)
  • searchElement : 要查找的元素
  • fromIndex:按指定的索引进行查找呈现的指定元素的第一个索引。<font style=”color:red”> 可选 </font>

    • 如果索引大于或等于数组的长度,则返回 -1
    • 如果提供的索引值为正数,则将其视为距数组开端的偏移量
    • 如果提供的索引为正数,依然从前到后搜寻数组
    • 如果提供的索引为 0,则将搜寻整个数组。
    • 默认值:0(搜寻整个数组)。
const arr = [1,1,2,3,4,5,4,4,6]

console.log(arr.indexOf(3));  //3
console.log(arr.indexOf(9));  //-1


console.log(arr.indexOf(3,4)); //-1
// 从索引为 4 的元素进行查找 3, 显然前面没有 3,返回 -1

数组去重

创立一个新的空数组,通过indexOf 来判断空数组是否第一次存在某个元素,

  • 不存在则返回 [< 0],push 到空数组中.
const newArr = []
arr.forEach(val => {if(newArr.indexOf(val) < 0){newArr.push(val)
    }
})
console.log(newArr);
// [1, 2, 3, 4, 5, 6]

lastIndexOf()

lastIndexOf() 查找数组中元素最初一次呈现的索引,如未找到返回 -1。

如果不存在则返回 -1。从数组的前面向前查找,从 fromIndex 处开始。

语法

arr.lastIndexOf(searchElement, fromIndex)
  • searchElement : 要查找的元素
  • fromIndex:按指定的索引进行查找呈现的指定元素的第一个索引。<font style=”color:red”> 可选 </font>

    • 从指定的索引地位 逆向 查找
    • 默认为数组的长度减 1(arr.length - 1),即整个数组都被查找。
    • 如果该值大于或等于数组的长度,则整个数组会被查找。
    • 如果为负值,数组依然会被从后向前查找。
    • 如果该值为负时,其绝对值大于数组长度,则办法返回 -1,即数组不会被查找。

留神

  • lastIndexOf 应用的是 严格相等 === 比拟 searchElement 和数组中的元素。
const arr = [1,1,2,3,4,5,4,4,6]

console.log(arr.lastIndexOf(4)); //7

console.log(arr.lastIndexOf(4,11));  
//7    指定的查找的索引 大于 数组的长度,会进行整个数组查找

console.log(arr.lastIndexOf(4,-33));
// -1   指定的索引为正数,且绝对值大于数组长度,则返回 -1

console.log(arr.lastIndexOf(4,-5));
//4    指定的索引为正数,且绝对值小于数组长度,则会 从向前进行查找

inCludes()

includes() 办法用来判断一个数组是否蕴含一个指定的值,依据状况,如果蕴含则返回 true,否则返回 false。

语法

arr.includes(searchElement, fromIndex)
  • searchElement : 要查找的元素

    查找时,辨别大小写

  • fromIndex:按指定的索引进行查找呈现的指定元素的第一个索引。<font style=”color:red”> 可选 </font>

    • 从指定的索引进行查找
    • 如果为负值,则按升序从 array.length + fromIndex 的索引开始搜
    • 如果 fromIndex 大于等于数组的长度,则会返回 false,且该数组不会被搜寻。
    • 默认为 0
const arr = [1,1,2,3,4,5,4,4,6]

console.log(arr.includes(4)); //true

console.log(arr.includes(4,66)); //false

console.log(arr.includes(1,-1)); //false

concat()

concat() 办法用于合并两个或多个数组。

语法

var new_array = old_array.concat([arr1][arr2])

留神

  • concat办法不会扭转 this 或任何作为参数提供的数组,而是返回一个 浅拷贝,它蕴含与原始数组相结合的雷同元素的正本

    • 对象援用(而不是理论对象):concat将对象援用复制到新数组中。原始数组和新数组都援用雷同的对象。也就是说,如果援用的对象被批改,则更改对于新数组和原始数组都是可见的。这包含也是数组的数组参数的元素。
    • 数据类型如字符串,数字和布尔(不是 StringNumberBoolean) 对象):concat将字符串和数字的值复制到新数组中。
let arr1 = [1,2,3]
let arr2 = [4,5,6]
let arr3 = [[1,2],[3,4]]
console.log(arr1.concat(arr2));
//[1, 2, 3, 4, 5, 6]

// 嵌套合并
console.log(arr1.concat(arr2).concat(arr3));
// [1, 2, 3, 4, 5, 6, [ 1, 2], [3, 4] ]


let obj1 = [{a:1},{b:2}]
let obj2 = [{c:3},{d:4}]
let obj3 = obj1.concat(obj2)  
console.log(obj3); 
//[{ a: 1}, {b: 2}, {c: 3}, {d: 4} ]


obj1[0].a = 4  // 扭转 obj[0]对象值,会间接影响合并后的数组,因为是浅拷贝
console.log(obj3); 
//[{ a: 4}, {b: 2}, {c: 3}, {d: 4} ]

toString()

toString() 返回一个字符串,示意指定的数组及其元素。

当一个数组被作为文本值或者进行字符串连贯操作时,将会主动调用其 toString 办法。

对于数组对象,toString 办法连贯数组并返回一个字符串,其中蕴含用逗号分隔的每个数组元素。

语法

arr.toString()
const arr = [1,2,3]

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

join()

join()办法通过连贯数组元素用逗号或指定的分隔符字符串分隔,返回一个字符串。

如果数组只有一项,则将在不应用分隔符的状况下返回该项。

语法

join()
join(separator)
  • separator : 指定的宰割的 字符 <font style=”color:red”> 可选 </font>
const arr = ['2021','08','08']

console.log(arr.join());     //2021,08,08
console.log(arr.join('-'));  //2021-08-08
console.log(arr.join('/'));  //2021/08/08

slice()

slice() 办法返回一个新的数组对象,这一对象是一个由 beginend 决定的原数组的 浅拷贝(包含 begin,不包含end)。原始数组不会被扭转。

语法

arr.slice(begin, end)
  • begin : 指定截取的 开始 索引 <font style=”color:red”> 可选 </font>

    • 默认从 0 开始
    • 如果begin 为正数,则以数组开端开始 的 绝对值开始截取 slice(-2) 开端第 2 个元素
    • 如果 begin 超出原数组的索引范畴,则会返回空数组。
  • end : 指定截取的 完结 索引 <font style=”color:red”> 可选 </font>

    • 如果 end 被省略,则 slice 会始终提取到原数组开端。
    • 如果 end 大于数组的长度,slice 也会始终提取到原数组开端。
    • 如果 end 为正数,则它示意在原数组中的倒数第几个元素完结抽取。
const arr = [11,22,33,44,55,66,77,88]

console.log(arr.slice(1,4));
// 应该返回 索引 1 - 3 的数组元素
// [22, 33, 44]


console.log(arr.slice(-4,2))  //[]

console.log(arr.slice(-4));   //[55, 66, 77, 88]


console.log(arr.slice(0,-1));
// [
//     11, 22, 33, 44,
//     55, 66, 77
//   ]

参考文献

Array – JavaScript | MDN

往期精彩文章

  • Vue 组件通信的 8 种形式
  • Vue3 + TypeScript 开发实际总结
  • Vue 权限路由 + 数据权限 最佳实际

最初

文章用下班时间肝了一周,写作不易,文中的内容都是 参考 MDN 文档。
如果喜爱的话能够点赞👍👍👍关注,反对一下,心愿大家能够看完本文有所播种!

正文完
 0