多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 数组常用的方法 ``` 增:push concat unshift 删:pop--单个后删 shift--单个前删 splice(index,个数) ---splice(0,2) 改:splice -- splice(0,2,item1,item2) 查:indexof includes length reverse--反转 slice--截取 join--转化为字符串 ``` ## 克隆 ` 4种` ``` var a = [1,8,6,8,5,4,1] ``` ``` var b = [] b = b.concat(a) ``` ***** ``` b = a.slice() ``` ***** ``` b = [...a] ``` ***** ``` var b = [] b.push(...a) ``` ## 数组遍历 `5种` > var a = [1,8,6,8,5,4,1] > var b = [ ] ``` a.forEach(e=>{ b.push(e) }) ``` ***** ``` for (const index in a) { b.push(a[index]) } ``` ***** ``` for (const e of a) { b.push(e) } ``` ***** ``` a.map(e=>{ b.push(e) }) ``` ***** ``` Array.from(a, e => { b.push(e) }) ``` ## 数组排序 `2种` ### 冒泡排序 ``` for (var i = 0; i < a.length; i++) { for (var j = 0; j < a.length - 1; j++) { if (a[i] < a[j]) { var temp = a[i]; a[i] = a[j]; a[j] = temp } } } console.log(a) ``` ### sort 升序 ``` a.sort() a.sort().reverse() --降序 ``` ## 取最值 ``` var max = a[0] for (const i in a) { if(max<a[i]){ max = a[i] } } ``` ## 取反 `reverse / for` ``` a.reverse ``` ``` for(var i = 0 ;i<a.length/2;i++){ var temp = a[i] a[i]=a[a.length-i-1] a[a.length-i-1] = temp } ``` ## 去重 `2种` ``` var b =[] for (const e of a) { if(!b.includes(e)){ b.push(e) } } ``` ***** ``` for (var i in a) { if(a.indexOf(a[i])==i){ b.push(a[i]) } } ``` ## 字符串去重成数组 > Set函数可以接受一个数组(或类似数组的对象)作为参数,用来初始化 > Set结构不会添加重复的值 > "abccaca" --> ["a", "b", "c"] --> "abc" ``` var e = [...new Set(a)].join("") new Set(a) --->转化成对象去重 [...new Set(a)] --->将对象解构成数组 [...new Set(a)].join("") --->数组转化成字符串 ```