js基础之Array类型常用方法
栈:LIFO(last-in-first-out)后进先出
队列:FIFO(first-in-first-out)先进先出
数组方法
arr.pop() 返回最后一项的值
arr.push() 在数组最糊一项追加,返回当前数组长度
arr.shift() 返回第一项的值
arr.unshift() 在数组前端插入1个或n个元素,返回当前数组长度
const arr = [1, 5,2,13,6]; let item1 = arr.pop() // item1 =6 arr-[1,5,2,13] let count1 = arr.push(7) // arr- [1,5,2,13,7] count1 = 5 let item2= arr.shift() // item2 = 1 let count2 = arr.unshift(9,8) // arr-[9,8,5,2,13,7] count2 = 6
数组排序
arr.reverse() 倒序当前数组
const arr = [1,5,25,23,111,42,99]; const arr1 = arr.reverse(); // arr1-[99, 42, 111, 23, 25, 5, 1], arr-[99, 42, 111, 23, 25, 5, 1] 原数组arr的值也发生了变化
arr.sort() 若不传入排序函数,会先将元素转变为字符串,然后按字符串排列方式排序,若为元素类型为数值类型,就不太准确
const arr = [1,5,25,23,111,42,99]; arr.sort(); // [1, 111, 23, 25, 42, 5, 99] 先转换为字符串,默认升序排列
如果要达到我们想要的按数字大小排列,需传入一个比较函数
const arr = [1,5,25,23,111,42,99]; console.log(arr.sort(function(a, b) { return a-b; // 升序排列,输出值[1, 5, 23, 25, 42, 99, 111]; b-a为降序排列 }));
arr.concat(arr0, arr1……)
const arr1 = [1, 2, 3] const arr2 = arr1.concat(4, [5, 6]); console.log(arr2) // [1, 2, 3, 4, 5, 6];
slice(start, end)
const arr = [1, 2, 3, 4, 5]; const arr1 = arr.slice(1, 4) // 1为数组起始index,4为结束index,第一个参数必须,第二个参数非必须,不传,默认到最后 console.log(arr1) // [2, 3,4]
splice(start, len, new1, new2)
const arr = [1, 2, 3, 4, 5]; const arr1 = arr.splice(1, 2, 6,7) // 第一个参数1为数组起始index,第二个2为删除数组长度,后面的参数6、7是删除指定长度元素后,紧跟着插入的新元素。若为第二个参数为0,则不删除,返回删除的元素 console.log(arr1) // [2,3] console.log(arr) // [1, 6, 7, 4, 5]
数组迭代方法
map(),对原数组做符合条件的操作,并返回;
filter(),只返回符合条件且为true的项
forEach() 没有返回
every() 每个项符合条件时返回true
some() 有一个符合条件就返回true
缩小减小
arr.reduce(function(pre, cur,index, arr) { return pre + cur})
查找数组最大/最小值
const arr = [1, 42, 39, 15, 3, 6, 87]; const max = Math.max.apply(Math, arr); // 最大值87 const min = Math.min.apply(Math, arr) // 最小值 1