js数组方法汇总

includes()

// 该方法用于判断数组是否存在某个元素
const arr = [1, 2, 3, 4, 5]
const includeNum4 = arr.includes(4)
const includeNum7 = arr.includes(7)
console.log(includeNum4) // true
console.log(includeNum7) // false

 forEach()

// 这是最常用的用来遍历数组的方法,需要注意的是该方法不会改变原数组,而且没有返回值。

const arr = [1,3,4,5,6,8]
arr.forEachI(item => {
  console.log(item)
})

map()

// map() 也是常用来遍历的方法,该方法会返回一个新的数组,但不会改变原数组,默认返回 undefined

const arr = [1,5,3,2,66]
const newArr = arr.map(item => item + 1)

console.log(newArr) // [2,6,4,3,67]

// 如果没有显式跟隐式返回值的话,得到的数组是所有元素都为 undefined 的数组

const arr = [1,5,3]
const newArr = arr.map((item, index)=> {console.log(item, index)})

console.log(newArr)// [undefined, undefined, undefined]

// 在 react 中这也常用来遍历生成 dom 节点,相信都很熟悉

const data = [1,2,3,7]

{
  data.map((item, index) => (
    <div key={index + Math.random()}>{item}</div>
  ))
}

// map 遍历之后尽量不用 index 作为返回值,最好用元素的 id 等

find()

// 该方法根据检索条件,找到数组中第一个满足条件的元素,若找不到则返回 undefined

const arr = [1,5,3,22,6]
const bigNum = arr.find(item => item > 6)

console.log(bigNum) // 22

findIndex()

// 该方法与find()类似根据检索条件,不同的是该方法返回的是索引

const arr = [1, 5, 3, 22, 6 ];
const bigNumIndex = arr.findIndex(item => item > 6)

console.log(bugNumIndex) // 3

filter()

 // 该方法顾名思义,这个方法就是用来过滤的,该方法返回一个新数组,不改变原数组

const arr = [1, 3, 5, 22, 6]
const filterItem = arr.filter(item => item % 2 === 0)

console.log(filterItem) // [22, 6]

push()和pop()

// push() 方法在数组末尾添加一个元素,返回数组的长度
const arr = [1,3,5]
const pushArrLen = a.push(7)

console.log(arr) // [1,3,5,7]  
console.log(pushArrLen) //   4

// pop() 方法删除数组最后一个元素并返回该元素
const arr = [1,3,5]
const popArrLen = a.pop()

console.log(arr) //  [1,3]  
console.log(popArrLen) // 5

unshift()和shift()

// unshift() 方法在数组开头添加一个元素,返回数组的长度
const arr = [1,3,5]
const unshiftArrLen = arr.unshift(7)

console.log(arr) // [7,1,3,5]  
console.log(unshiftArrLen) // 4

// shift() 方法删除数组第一个元素并返回该元素
const arr = [1,3,5]
const shiftArrLen = a.pop()

console.log(arr) // [3,5]  
console.log(shiftArrLen) // 1

concat()

// concat() 方法在一个数组后面拼接新的元素,可接收 n 个参数,参数可以是任意数据类型,如果是数组,则将数组跟原数组拼接,如果是其他数据类型,则将该元素添加到原数组后面

// 该方法不改变原数组,会返回拼接好的新数组,因此可以 执行 链式操作

const arr = [1,3,5]

const concatArr = arr.concat(2,4).concat(6,7,8).concat('hello world').concat(() => {}, [9,10,[11,12]])

console.log(arr) // [1,3,5]
console.log(concatArr) // [1, 3, 5, 2, 4, 6, 7, 8, 'hello world', () => {}, 9, 10, [11, 12]]

reverse()

// reverse() 方法将一个数组倒置,该方法返回新的数组,且会改变原数组

const arr = [1, 2, 3, 4]
const reverseArr = arr.reverse()

console.log(arr) // [4, 3, 2, 1] 
console.log(reverseArr) // [4, 3, 2, 1]

sort()

// sort() 方法用于将数组排序,可以接收一个函数作为参数,当不传递参数时,sort 将按照内部定义的生序的规则进行排序,该方法返回排序后的数组,原数组将被改变。

const arr = [[() => {}], [12], '4', [11], 123, 'hello', n => n + 1, () => {}, 1, []]

const sortArr = a.sort()

console.log(sortArr) // [[], () => {}, [() => {}], 1, [11], [12], 123, '4', n => n + 1, 'hello']

// 默认的排序算法是调用每个数组项的 toString() 转型方法,比较得到的字符串的编码大小,按照最小值在前面,最大值在后面的方式排序。也就是正序,与 

sortArr = arr.sort((c, d) => c - d)

// 等价,倒序为

sortArr = arr.sort((c, d) => d - c)

// 举例:

const arr = [
  { id: 4, name: 'michael' },
  { id: 2, name: 'kangkang' },
  { id: 3, name: 'meria' },
  { id: 1, name: 'jane' },
]

const newArr = arr.sort((a, b) => b.id - a.id)

console.log(newArr) // [{ id: 4, name: 'michael' },{ id: 3, name: 'meria' },{ id: 2, name: 'kangkang' },{ id: 1, name: 'jane' }]

join()和split()

// join() 方法将数组的元素组起一个字符串,以separator为分隔符,省略的话则用默认用逗号为分隔符,该方法只接收一个参数:即分隔符,该方法返回拼接后的字符串,不改变原数组。

const arr = [1, 3, 'hello']

const newArr = arr.join('-')

console.log(newArr) // '1-3-hello'

// 通过join()方法可以实现重复字符串,只需传入字符串以及重复的次数,就能返回重复后的字符串

const repeatStr = (str, n) => new Array(n).join(str)

const newStr = repeatStr('hi', 3)

console.log(newStr) // 'hihihi'


// split() 方法将一个字符串分割为数组,接收一个参数,以该参数为分割符

const str = 'charming javascript'

const strArr1 = str.split('')
const strArr2 = str.split('j')
      
console.log(strArr1) // ["c", "h", "a", "r", "m", "i", "n", "g", " ", "j", "a", "v", "a", "s", "c", "r", "i", "p", "t"]
console.log(strArr2) //  ['charming ', 'avascript']

every()和some()

// every() 方法接收一个函数作为参数,判断数组中每一项都是否满足条件,只有所有项都满足条件,才会返回true。
const arr = [1,5,2,4,11]
const isBig = arr.every(item => item > 5)
const isSmall = arr.every(item => item < 20)
console.log(isBig) //  true 
console.log(isSmall) // false

// some() 方法接收一个函数作为参数,数组中只要有一项满足条件,则返回 true,如果都不满足条件,则返回 false
const arr = [
    { price: 10, name: 'apple' },
    { price: 20, name: 'orange' },
    { price: 15, name: 'banana' }
]
const isCheap = arr.some(item => item.price < 15)
const isExpensive = arr.some(item => item.price > 20)
console.log(isCheap) // true 
console.log(isExpensive) // false

indexOf()和lastIndexOf()

// 两个方法都用来查找索引,接收两个参数,第一个参数是要查找的元素,第二个参数是查找的起始位置(默认第一项和最后一项的位置)。都会返回该元素的正索引,不同的是当有第二个参数时,indexOf() 只查找该元素之后的元素,lastIndexOf() 只查找该元素之前的元素。若找到该元素则返回索引,若找不到则返回 -1

const arr = [1, 3, 5, 7, 9]
const index = arr.indexOf(7, 0)
const lastIndex = arr.lastIndexOf(7, 2)

console.log(index) // 3
console.log(lastIndex) // -1

slice()

// splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。该方法会改变原始数组。

splice(index, howmany, item1, item2...itemx)
const arr = [1, 2, 3, 4, 5]
const spliceArr = arr.splice(2, 3, 6, 7, 8)

console.log(arr) // [1, 2, 6, 7, 8]  
console.log(spliceArr) // [3, 4, 5]

reduce()

// reduce() 方法很强大
// 语法arr.reduce(callback, initialValue)
// reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce 的数组。也就是:
arr.reduce((prev, current, index, array) => {}, initialValue)
// 下面看一些 reduce 的应用
// 数组求和:
const arr = [1,2,3,4,5]
const sum = arr.reduce((prev, current) => prev + current, 0)        console.log(sum) // 15

// 数组求积:
const arr = [1,2,3,4,5]
const pow = arr.reduce((prev, current) => prev * current, 1)        console.log(pow) // 120

// 数组去重:
const arr = [1,3,4,2,5,3,4]
const slimArr = arr.reduce((prev, current) => {
  if(prev.includes(current)) {
    return prev
  } else {
    return prev.concat(current)
  }
}, [])

// 求字符串的字节长度:
const str = 'charming javascript'
const byteLen = str.split('').map(item => item.charCodeAt() > 255 ? 2 : 1).reduce((prev, current) => prev + current, 0)

// 求对象里的数乘积再求和:
const fruitArr = [
 { name: 'apple', price: 10, quantity: 2 },
 { name: 'orange', price: 15, quantity: 4 },
 { name: 'banana', price: 5, quantity: 3 },
]
const totalPrice = fruitArr.reduce((prev, current) => {
 return prev + current.price * current.quantity
}, 0)

有任何补充请联系我及时添加

原文地址:https://www.cnblogs.com/wuxu-dl/p/15083385.html