Array数组常用方法(含es6)介绍

数组中提供了一系列元素相关的API操作,其中有

三个静态 api:

  • Array.from()
  • Array.isArray()
  • Array.of()

三十一个原型 api:

  • Array.prototype.concat()
  • Array.prototype.copyWithin()
  • Array.prototype.entries()
  • Array.prototype.every()
  • Array.prototype.fill()
  • Array.prototype.filter()
  • Array.prototype.find()
  • Array.prototype.findIndex()
  • Array.prototype.flat()
  • Array.prototype.flatMap()
  • Array.prototype.forEach()
  • Array.prototype.includes()
  • Array.prototype.indexOf()
  • Array.prototype.join()
  • Array.prototype.keys()
  • Array.prototype.lastIndexOf()
  • Array.prototype.map()
  • Array.prototype.pop()
  • Array.prototype.push()
  • Array.prototype.reduce()
  • Array.prototype.reduceRight()
  • Array.prototype.reverse()
  • Array.prototype.shift()
  • Array.prototype.slice()
  • Array.prototype.some()
  • Array.prototype.sort()

本文整理了自己所用过的数组方法,包括新增的es6语法。

1、Array.from()

将一个类数组或可遍历对象,转换成一个新的浅拷贝的数组实例。

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
}
let arr2 = Array.from(arrayLike)
console.log(arr2) //['a', 'b', 'c']

console.log(Array.from('foo')) // ["f", "o", "o"]

该方法还可以接收第二个参数,作用类似于数组的 map 方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

let arrayLike = {
    '0': 1,
    '1': 2,
    length: 2
}
let newArr = Array.from(arrayLike, item => item * 2)
console.log(newArr) //[2, 4]

2、Array.isArray()

用于检测是否是一个 Array。

语法:Array.isArray(obj)  参数:obj 需要检测的值

返回值:如果检测的值是 Array,则返回 true,否则返回 false

Array.isArray([1, 2, 3]) // true
​
Array.isArray({foo: 123}) // false

3、concat()

合并两个或多个数组。此方法不会更改原数组,而是返回一个新数组。

const arr1 = ['a', 'b', 'c']
const arr2 = arr1.concat(['d', 'e', 'f'])
​
console.log(arr2) // ["a", "b", "c", "d", "e", "f"]

4、entries()

遍历数组的键和值

const arr = ['a', 'b', 'c'];
const iterator = arr.entries();
for (let e of iterator) {
    console.log(e);   // [0,'a'] [1,'b'] [2,'c']
} 

5、every()

所有的,每一个。检测数组中的所有元素是否满足指定条件,如果有一个元素不满足,则整个表达式返回 false,且剩余的元素不会再进行检测,要所有的元素都返回了true,结果才是true。every 方法也不会改变原数组。

注意:如果检测的是一个空数组,在任何情况下返回的都是 false

const arr = [1, 30, 39, 29, 10, 13]
const fn = (currentValue) => currentValue < 40
​
console.log(arr.every(fn)) // true

6、filter()

过滤数组,返回一个满足条件的新数组。

语法:

arr.filter((item,index,arr) => { // value当前元素,index索引,arr原数组
    // statements
}) 

例:

// 及格的留下来, 没及格的出门右拐
const students = [
    { name: 'zs', score: 90 },
    { name: 'ls', score: 30 },
    { name: 'ww', score: 10 },
    { name: 'zl', score: 100 },
    { name: 'tq', score: 70 },
    { name: 'wb', score: 60 }
]
​
const result = students.filter(item => {
    return item.score >= 60
})
console.log(result)

7、find()

找到第一个满足条件的元素。没有则返回undefined。

const arr = [5, 12, 8, 130, 44]
const found = arr.find(item => item > 10)
​
console.log(found) // 12

8、findIndex()

返回第一个满足条件的元素的索引。没找到则返回-1。

const arr = [5, 12, 8, 130, 44]
const isExist = (element) => element > 13
​
console.log(arr.findIndex(isExist)) // 3

9、forEach()

遍历数组,然后执行一次给定的函数。

注意:forEach() 没有返回值,本质上等同于 for 循环

const arr = ['毛利兰', '柯南', '小五郎', '灰原哀']
​
const newArr = []
arr.forEach(item => {
    const temp = <h5>{item}</h5>
    newArr.push(temp)
}) 

10、includes()

判断数组中是否包含指定的值,如果包含则返回 true,否则返回false。

const pets = ['cat', 'dog', 'bat']
​
console.log(pets.includes('cat')) // true
console.log(pets.includes('at')) // false

11、indexOf()

返回数组中找到的给定元素的第一个索引,如果不存在,则返回-1。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']
​
console.log(beasts.indexOf('bison')) // 1
​
// start from index 2
console.log(beasts.indexOf('bison', 2)) // 4
​
console.log(beasts.indexOf('giraffe')) // -1 

12、lastIndexOf()

同indexOf()功能一样,只不过从数组的后面向前查找,即返回在数组中最后一个的索引。

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
console.log(animals.lastIndexOf('Dodo')) // 3
​
const arr = [1,2,3,4,5,2]
console.log(arr.lastIndexOf(2))  // 5 

13、join()

将数组中的元素连接成一个字符串并返回。

const elements = ['Fire', 'Air', 'Water']
​
console.log(elements.join()) // "Fire,Air,Water"
console.log(elements.join('-')) // "Fire-Air-Water" 

14、keys()

遍历数组元素的键名。

const arr = ['a', 'b', 'c']
const iterator = arr.keys()
​
for (const key of iterator) {
    console.log(key) // 0, 1, 2
} 

15、values()

遍历数组元素的键值。

const arr = ['a', 'b', 'c']
const iterator = arr.values()
​
for (const value of iterator) {
    console.log(value) // 'a', 'b', 'c'
} 

16、map()

遍历数组,并返回一个新数组,新数组中包含每次回调函数返回的结果,一比一的得到一个新数组。

语法:

arr.map((value,index,arr) => { //value当前元素,index索引,arr原数组
    // statements
})

例:

const arr = ['毛利兰', '柯南', '小五郎', '灰原哀']
​
// const newArr = arr.map(item => <h5>{item}</h5>)
const newArr = arr.map(item => {
    return <h5>{item}</h5>
}) 

17、pop()

删除数组中最后一个元素,并返回该元素的值。此方法会更改原数组。

const plants = ['broccoli', 'cabbage', 'kale', 'tomato']
​
console.log(plants.pop()) // "tomato"
​
console.log(plants) // ["broccoli", "cabbage", "kale"] 

18、push()

在数组的末尾添加一个或多个元素,并返回添加后的数组长度。该方法会改变原数组。

const animals = ['pigs', 'goats', 'sheep']
const count = animals.push('cows')
​
console.log(count) // 4
console.log(animals) // ["pigs", "goats", "sheep", "cows"] 

19、reduce()

方法对数组中的每个元素执行提供的reducer函数,并将其结果计算为一个返回值。更多详细用法请点这里

const arr = [1, 2, 3, 4]
const reducer = (accumulator, currentValue) => accumulator + currentValue
​
console.log(arr.reduce(reducer)) // 10 = 1 + 2 + 3 + 4
​
console.log(arr.reduce(reducer, 5)) // 15 = 5 + 1 + 2 + 3 + 4

20、reverse()

将数组中的元素反转,并返回该数组。该方法会改变原数组。

const arr = ['one', 'two', 'three']
const reversed = arr.reverse()
​
console.log(reversed) // ["three", "two", "one"] 

21、shift()

删除数组中的第一个元素,并返回该元素的值。此方法会改变原数组。

const arr = [1, 2, 3]
const firstElement = arr.shift()
​
console.log(arr) // [2, 3]
console.log(firstElement) // 1  

22、slice()

该方法返回一个新数组,由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。不改变原数组。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
​
console.log(animals.slice(2)) // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)) // ["camel", "duck"]  

23、some()

检测数组中满足指定条件的元素,只要回调函数中有一个或以上返回了 true, 整个结果就是 true。

注意:如果检测的是一个空数组,在任何情况下返回的都是 true 。

const array = [1, 2, 3, 4, 5]
const even = (element) => element % 2 === 0
​
console.log(array.some(even)) // true  

24、sort()

用原地算法对数组元素进行排序,并返回新数组。默认排列顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。

const months = ['March', 'Jan', 'Feb', 'Dec']
console.log(months.sort()) // ["Dec", "Feb", "Jan", "March
​
const arr = [1, 30, 4, 21, 100000]
console.log(arr.sort()) // [1, 100000, 21, 30, 4]

25、splice()

删除指定索引值之后的一个或多个元素或添加新元素。此方法会改变原数组。

// 删除:第一个参数是从下标为几的元素开始删除,第二个参数为删除几个元素
var arr = [1, 2, 3, 4, 5]
var res = arr.splice(1, 2) // 从索引为1开始删除两个
console.log(arr) // [1,4,5]
console.log(res) // [2,3]
​
​
// 添加:第二个参数设为0,添加第三个参数,表示再插入一个数在指定下标数前面,返回值是空数组
var arr = [1, 2, 3, 4, 5]
var res = arr.splice(2, 0, 6) // 第二个参数为0,在索引为2的前面添加6
console.log(arr) // [1,2,6,3,4,5]
console.log(res) // []
​
​
// 替换:先删再加,表示替换,返回值是被删除的元素组成的数组
var arr = [1, 2, 3, 4, 5]
var res = arr.splice(1, 2, 100, 200, 300, 400, 500) // 从索引为1开始删除两个,再添加后面的数据
console.log(arr) //[1,100,200,300,400,500,4,5]
console.log(res) //[2,3]  

26、unshift()

在数组的前面添加一个或多个元素,返回值为添加后的新数组长度。该方法会修改原数组。

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

27、toString()

将数组元素转换成一个字符串并返回

const array1 = [1, 2, 'a', '1a']
console.log(array1.toString()) // "1,2,a,1a"

 

总结:

会改变原数组的方法:push()、pop()、reverse()、sort()、splice()、shift()、unshift()

 

* forEach():让每一个元素执行一次函数,没有返回值,相当于for循环。不会占用全局变量,结合箭头函数贼舒服

* map():返回一个新数组,长度和原数组一样。

filter():返回一个新数组,保留那些满足条件的(即返回值是true的元素)

* some():得到一个布尔值,只要函数中有一个返回true,整体结果就是true

* every():得到一个布尔值,所有的函数都返回true,结果就是true

* includes():返回一个布尔值,如果包含指定值,则返回true

indexOf(),findIndex():得到一个数值,返回找到的第一个元素的索引值,不存在则返回-1

 

posted @ 2020-09-29 16:45  sugar_coffee  阅读(925)  评论(0编辑  收藏  举报