一、数组的介绍
javascript中数据集合有:数组、对象、Map集合、Set集合,数组中可以包括任意数据类型。
二、创建数组方式
-
1、使用字面量创建
let arry = ['哈哈', '你好', 1, 2, {'name': '哈哈'}]; -
2、使用类的实例创建
let array = new Array('哈哈', 1, 24, {'name': '男', 'gender': '男'});
三、修改数组的方式
-
1、使用
push()尾部追加数组可以一次追加一个也可以一次性追加多个,使用
push后的返回值是数组的长度let ary = [1,2,3,4]; ary.push(21, 12); -
2、使用
unshift()头部追加数组跟
push一样的可以一次追加多个元素,返回的值是当前数组的长度ary.unshift(12,12); -
3、使用
pop()删除数组最后一个 -
4、使用
shift()删除数组第一个元素 -
5、使用
splice()删除元素、添加元素-
当传递参数是一个参数的时候(默认第二个参数为数组长度)
-
当传递是两个参数的时候是删除元素(第一个参数表示从什么下标开始, 删除数组的元素个数),返回值是被删除的元素
let ary = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let result = ary.splice(2, 4); // result = [3, 4, 5, 6] // ary = [1, 2, 7, 8, 9]; -
当传递的参数是大于等于三个的时候(返回值跟上面的一样)
var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9]; ary.splice(1, 1, '哈哈'); // 相当于直接替换一个,从第一个元素开始到第一个元素, ary.splice(1, 2, '哈哈', '哈哈', '呵呵'); // 从第一个个元素开始删除两个元素,用后面的几个元素来填充 ary.splice(1, 2, ['哈哈', '嘻嘻', '呵呵']) // 第三个参数可以是集合
-
-
6、
slice()提取数据,不修改原来数据var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9]; ary.slice(1,3); // 返回2, 3 -
7、
delete删除数组删除数组,但是数组长度不变,只是被删除的位置是
emptylet ary = [1, 2, 3, 4]; delete ary[1]; console.log(ary); -
8、总结:
- 1.如果要修改数组的时候劲量使用
pop或push这样仅仅是改变数组最后一位 - 2.
shift、unshift、splice会改动数组的位置,性能要低点
- 1.如果要修改数组的时候劲量使用
四、数组遍历
-
1、传统的
for遍历 -
2、
ES6中for..of遍历let ary3 = ['哈哈', '嘻嘻', '呵呵']; // 直接使用 for(let item of ary3){ console.log(item); } // 带序列号的 for(let [index, item] of ary3.entries()){ console.log(index, item); } // 使用keys for (let index of ary3.keys()){ console.log(index, ary3[index]); } // 使用values() for(let k of ary3.values()){ console.log(k) } -
3、使用
forEach()遍历,无返回值// forEach定义:forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; ary3.forEach((item, index, ary) => { console.log(item, index, ary) });
五、映射数组
-
1、
map()返回新的数组// map定义: map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; let ary4 = ary3.map((item, index, ary) => { })
六、测试数组
-
1、
some()一个返回true就返回truesome定义:some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; -
2、
every()一个返回false就返回false``every定义: every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;`
-
3、
Array.isArray(数组)判断是否为数组
七、数组查找
-
1、
find()查找第一个返回的结果let ary3 = ['哈哈', '嘻嘻', '呵呵']; let res = ary3.find((item, index, ary) => { console.log(item, index, ary) return item == '哈哈'; }); console.log(res) -
2、
findIndex()返回第一个序列号let res2 = ary3.findIndex((item, index, ary) => { return item == '嘻嘻'; }); console.log(res2); -
3、
indexOf(查找的元素, 开始查找位置)查找返回序列号,如果没有查找到就返回-1// indexOf定义方式: indexOf(searchElement: T, fromIndex?: number): number; ary.indexOf(1, 2) -
4、
lastIndexOf()与indexOf()一样的 -
5、
filter()过来数组,返回的一个新数组let ary4 = [12, 13, 30, 1, 4, 6, 2, 7, 9, 10]; let res4 = ary4.sort((a, b) => a - b); console.log(res4); let res5 = ary4.filter((item, index ,ary) => { return item > 5; }); console.log(res5); -
6、
includes()查找一个元素是否在数组中ary4.includes(查找的元素, 起始位置[可以不写]);
八、数组的排序
-
1、
sort()排序// 源码定义方式:sort(compareFn?: (a: T, b: T) => number): this
九、合计数组
-
1、
reducer()的使用/** * reduce(函数, 初始化值) * 其中函数的参数(计算后的结果, 当前值, 当前值的序列号, 数组) */ let result = [1, 2, 3, 4, 5].reduce((total, currentVal, currentIndex, ary) => { console.log(total) return total + currentVal }, 0) console.log(result)
十、数组的转换
-
1、
Array.from()可以将类数组、可迭代对象转换为数组
Array.from('hello') // ['h', 'e', 'l', 'l', 'o'] let namesSet = new Set(['a', 'b']) Array.from(namesSet) // ['a', 'b'] -
2、
...转换为数组[...'hello'] ["h", "e", "l", "l", "o"] -
3、
Array.of()方法用于将一组值,转换为数组Array.of(3, 11, 8) // [3,11,8] -
4、
join()数组转换为字符串[...'hello'].join('') -
5、
split()是字符的方法,转换为数组 -
6、
toString()只是join()的简化版(用,连接数组)
十一、数组的拷贝
-
1、
concat()方法不改变原来数组,返回一个新数组- 1.如果
concat()里面不传递参数表示数组的拷贝 - 2.如果
concat()里面含有参数,或者集合都是合并到新数组中
- 1.如果
-
2.
copyWithin()数组内部的复制,直接修改了原数组,返回当前数组/** * Array.prototype.copyWithin(target, start = 0, end = this.length) * target: 是必须的,表示要替换的位置 * start: 表示数组内从哪里开始取值 * end: 表示数组内取值结束位置 * 如果是负数就用数组长度 + 负数值 * */ let ary5 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; // 把第八个元素拷贝替换到第二个位置上 ary5.copyWithin(2, 8, 9); console.log(ary5); // 把从第六位开始到最后拷贝到第二位, ary5.copyWithin(2, 5); console.log(ary5);
十二、网上比较常用的方法
-
1、数组最大值
const arrMax = (arr) => Math.max.apply(null, arr); -
2、数组最小值
const arrMin = (arr) => Math.min.apply(null, arr); -
3、数组随机排序
const shuffle1 = (target) => { function randomsort(a, b) { return Math.random() > .5 ? -1 : 1; //用Math.random()函数生成0~1之间的随机数与0.5比较,返回-1或1 } return target.sort(randomsort); }; -
4、数组中随机取出一个值
const randomItem = (ary) => { return ary[Math.ceil(Math.random() * ary.length)]; } -
5、判断数组中是否有重复的值
const isRepeat: function(arr) { //arr是否有重复元素 var hash = {}; for(var i of arr) { if(hash[arr[i]]) return true; hash[arr[i]] = true; } return false; } -
6、数组去重(根据对象
key不能重复)const unique = (ary) => { var result = [], hash = {}; for(var i = 0, elem; (elem = arr[i]) != null; i++) { if(!hash[elem]) { result.push(elem); hash[elem] = true; } } return result; }; -
7、使用
ES6新方法去重const unique = (ary) => [...new Set(ary)];
十三、扩展数组原型(不建议直接扩展)
-
1、查看数组本来的方法属性
console.dir(Array.prototype) -
2、自己重写数组的
forEach方法Array.prototype.myForEach = function (fn) { for (let [index, item] of this.entries()) { fn(item, index, this); } }; [1, 2, 3, 5].myForEach((item, index ,ary) => { console.log(item, index, ary); }) -
3、自己重写
map方法Array.prototype.myMap = function (fn) { let result = []; for (let [index, item] of this.entries()) { result.push(fn(item, index, this)); } return result; }; let result1 = [1,2,3,4].myMap((item, index, ary) => { return item * 2; }); console.log(result1); -
4、自己重写
reduce方法Array.prototype.myReduce = function(fn, initVal) { let total; if (initVal != undefined) { total = initVal; } else { total = this[0]; } if (initVal === undefined) { for (let i = 1; i < this.length; i++) { total = fn(total, this[i], i, this); } } else { for (let [index, val] of this.entries()) { total = fn(total, val, index, this); } } return total; }; let result1 = [1, 2, 3, 4, 5].myReduce((total, currentVal) => { return total + currentVal; }); console.log(result1); -
5、判断一个数组是否包含在另外一个数组里面
/** * 判断一个数组元素是不是在数组里面 * @param obj * @returns {boolean} */ Array.prototype.contains = function(obj) { var i = this.length; while(i--) { if(this[i] === obj) { return true; } } return false; }; -
6、如果自己喜欢可以把自己想要的方法放到原型上