felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

JavaScript 常用的数组操作方法总结 #208

Open felix-cao opened 3 years ago

felix-cao commented 3 years ago

一、7个改变原数组的方法

ID Methods Tips Return Syntax
1 push 在数组末尾添加一个或多个元素 返回数组长度 array.push(item1, item2, ..., itemX)
2 pop 删除数组的最后一个元素 返回被删的最后一个元素 array.pop()
3 unshift 向数组的开头添加一个或多个元素 返回数组长度 array.unshift(item1,item2, ..., itemX)
4 shift 删除数组的第一个元素 返回被删的第一个元素 array.shift()
5 splice 删除元素,并添加新元素。 返回被删除的元素 array.splice(index, howmany, item1, ....., itemX)
6 sort 对数组的元素进行排序并返回 返回数组 array.sort(sortfunction)
7 reverse 颠倒(反转)数组中元素的顺序并返回 返回数组 array.reverse()

这几个方法叫做 Mutation Methods 变更方法,在 Vue 的数组更新检测 中,Vue 将这几个方法进行了包裹,以实现数组的变化触发视图的更新。

二、不改变原数组

ID Methods Tips Return Syntax
1 concat 合并两个或更多的数组 返回合并结果 array1.concat(array2,array3,...,arrayX)
2 slice 从数组中选择元素 返回选取的元素 array.slice([start], [end])
3 filter 过滤数组元素 返回符合条件的新数组 array.filter(function(currentValue,index,arr), [thisValue])
4 forEach() 为每个数组元素调用函数 undefined array.forEach(function(currentValue, index, arr), [thisValue])
5 map 为每个数组元素调用函数 新数组 array.map(function(currentValue, index, arr), [thisValue])
6 some 检查数组中的任何元素是否通过测试 Boolen array.some(function(currentValue, index, arr), [thisValue])
7 reduce 将数组元素计算为一个值(从左到右) 累积结果 array.reduce(function(total, currentValue, currentIndex, arr), [initialValue])

JavaScript 数组实例方法 reduce 使用技巧

三、ES6 中新增的数组方法

ID Methods Tips Return Syntax
1 Array.from 类数组对象转为对象 数组对象 Array.from(object, [mapFunction], [thisValue])
2 Array.of 将一组值转为数组 返回数组
3 copyWithin 修改原数组并返回 Array.prototype.copyWithin(target, start = 0, end = this.length)
4 find
5 findIndex
6 entries
7 keys
8 values
9 includes
10 flat

类数组对象:拥有 length 属性的对象或可迭代,如字符串、DOM对象

Reference