🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 数组排序 ``` var a = [1, 54, 33, 556, 3334, 11] ``` ### 1.冒泡排序 ``` 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) ``` ### 2.js内置对象排序 ``` var a = [1, 54, 33, 556, 3334, 11] a.sort(function(i,j){ return i - j; }) console.log(a) ``` ## 去偶数合集 ``` var temp = [ ] for(var i = 0;i<a.length;i++){ if(a[i]%2==0){ temp.push(a[i]); } } console.log(temp) ``` ## 取最大,小值 ``` <script> var arr = [1,3,2,5,10,100,50]; var max = arr[0]; for(var i=0;i<arr.length;i++){ if(max<arr[i]){ max=arr[i] } } console.log(max); </script> ``` ## 取反 ``` console.log(a) var temp = []; for(var i = 0;i<a.length/2;i++){ var b = a[i] a[i]= a[a.length-i-1] a[a.length-i-1] = b; } console.log(a) ``` ## 数组去重 ~~~ 1.新建一新数组,遍历旧数组,值不在新数组就push进该新数组中 !temp.includes(array[i]) 2.根据数组下标去重 :如果当前数组的第i项在当前数组中第一次出现的位置是i, 才存入数组;否则代表是重复的array.indexOf(array[i]) == i 3.遍历数组 :元素0与右边的元素依次比较,若元素有重复,则结束元素0比较,将下一个元素1当做比较对象。直到没有重复再加入新数组,在进行下一次的比较(比较从加入数组的元素i开始) if (array[i] === array[j]){   i++;   j = i;   } ~~~ ### 1.判断值是否在数组中 ``` var array = [1, 5, 7, 8, 5, 4, 3, 9, 7]; var newarr = [] for (var i = 0, j = array.length; i < j; i++) { if (newarr.indexOf(array[i]) === -1) { /* if (!newarr.includes(array[i]) ) { */ newarr.push(array[i]); } } console.log(newarr) ``` ### 2.判断当前值在数组中的下标是否为当前下标 ``` var array = [1, 5, 7, 8, 5, 4, 3, 9, 7]; var newarr = [] for (var i = 0, j = array.length; i < j; i++) { if (array.indexOf(array[i]) == i) { newarr.push(array[i]); } } console.log(newarr) ``` ### 3.优化遍历法 ``` var ar = [1, 5, 7, 8, 5, 4, 3, 9, 7]; var temp = []; for (var i = 0; i < ar.length; i++) { for (var j = i + 1; j < ar.length; j++) { if (ar[i] === ar[j]) { i++; j = i; } } temp.push(ar[i]); } console.log(temp) ``` ## 数组复制 ``` var a = [1,2,3,4] var b = [] /* a.forEach(e => { b.push(e) }); */ /* b = [...a] */ /* b = b.concat(a) */ /* b.push(...a) */ /* b = a.slice(0) */ console.log(b) ``` ## 数组遍历 ``` a.forEach(element => { b.push(element) }); ``` ``` //可以用于object遍历 for (let i in a) { b.push(a[i]) } ``` ``` for (let i of a) { b.push(i) } ``` ``` a.map(e=>{ b.push(e) }) ``` ``` Array.from(a,e=>{ b.push(e) }) console.log(b) ``` ## 字符串去重成数组 > Set函数可以接受一个数组(或类似数组的对象)作为参数,用来初始化 > Set结构不会添加重复的值 > "abccaca" --> ["a", "b", "c"] --> "abc" ``` var e = [...new Set(a)].join("") new Set(a) --->转化成对象去重 [...new Set(a)] --->将对象解构成数组 [...new Set(a)].join("") --->数组转化成字符串 ```