冒泡排序:依次从数组中相邻数字进行比较(两两比较),大的放后面。冒泡排序每次比较都有可能会操作一次数组。
以下是基本代码:
let arr = [4, 8, 7, 9, 6, 21, 54];
for (let i = 0; i <= arr.length - 1; i++) {
for (let j = 0; j <= arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let x = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = x;
}
}
}
console.log(arr)
数组去重:
let arr = fn([1, 1, 2, 3, 5, 5, 6, 9, 8, 7, 4, 5, 4, 9]);
function fn(arr) {
let arr1 = [];
for (let i = 0; i < arr.length; i++) {
if (arr1.indexOf(arr[i]) === -1) {
arr1.push(arr[i]);
}
}
return arr1;
}
console.log(arr);
以上是用js原生代码写数组去重,在ES中增加了set方法,用来数组去重更加方便,以下是代码:
const arr = [3,4,5,6,5,4,3,3,4,5,6,6,6];
const a = [...new Set(arr)];
console.log(a)