JavaScript对象数组常用方法

278 阅读1分钟

Array.length

// 数组长度 length是Array的实例属性
const arr = ['a', 'b', 'c']
console.log(arr.length) // 3

concat()

// 合并两个或多个数组 创建新数组
const arr1 = ['a', 'b', 'c']
const arr2 = ['d', 'e', 'f']
const arr3 = arr1.concat(arr2)
console.log(arr3) // ['a', 'b', 'c', 'd', 'e', 'f']

filter()

// 过滤 返回满足条件的所有值 创建新数组
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']
const result = words.filter(res=> res.length > 6)
console.log(result) // ["exuberant", "destruction", "present"]

find()

// 返回满足条件的第一个值,否则返回undefined
const array1 = [5, 12, 8, 130, 44]
const found = array1.find(res => res > 10)console.log(found) // 12

findIndex()

// 返回满足条件第一个元素的索引,若没有则返回-1
const array1 = [5, 12, 8, 130, 44]
const found = array1.findIndex(res => res > 13)
console.log(found) // 3

forEach()

// 循环 对每个元素执行一次
const array1 = ['a', 'b', 'c']
array1.forEach(res=> console.log(res)) // a b c

map()

// 创建新数组 数组中的每个元素是调用一次提供的函数后的返回值
const array1 = [1, 4, 9, 16]
const map1 = array1.map(x => x * 2)
console.log(map1) // [2, 8, 18, 32]

reduce(callback, initialValue)

// 累加器
// 参数:callback回调函数 
// previousValue 上一次调用回调返回的值,或者是提供的初始值(initialValue)
// currentValue 数组中当前被处理的元素
// index 当前元素在数组中的索引
// array 调用 reduce 的数组
// initialValue 作为第一次调用 callback 的第一个参数
const array1 = [1, 2, 3, 4]
const total = array1.reduce((a, b)=>{ return a + b })
console.log(total) // 10

sort()

// 排序 按照字符编码的顺序进行排序
const array1 = [1, 30, 4, 21, 100000]
array1.sort()
console.log(array1) // Array [1, 100000, 21, 30, 4]

slice(start, end) 

// 截取 包括start 不包括end
const data = ['a', 'b', 'c']
console.log(data.slice(0, 1)) // a b