精选JavaScript小技巧:常见算法与数据结构
JavaScript常见算法与数据结构小技巧
本文将介绍一些在JavaScript开发中常用的算法与数据结构小技巧,帮助读者提高编程效率,优化代码质量,提升数据处理能力。
- 数组去重 在实际开发中,数组去重是一个常见的需求。可以使用Set对象或者双层循环实现数组去重。
// 使用Set对象
const arr = [1, 2, 3, 4, 4, 5, 6];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5, 6]
// 使用双层循环
function unique(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
}
const uniqueArr = unique([1, 2, 3, 4, 4, 5, 6]);
console.log(uniqueArr); // [1, 2, 3, 4, 5, 6]
- 查找数组中的元素索引 查找数组中元素的索引,可以使用indexOf方法,时间复杂度为O(n)。
const arr = [1, 2, 3, 4, 5];
const index = arr.indexOf(3);
console.log(index); // 2
- 冒泡排序 冒泡排序是一种简单的排序算法,通过重复遍历数组,比较相邻元素并交换位置,直到没有需要交换的元素为止。
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
const arr = [5, 2, 9, 1, 5, 6];
const sortedArr = bubbleSort(arr);
console.log(sortedArr); // [1, 2, 5, 5, 6, 9]
- 快速排序 快速排序是一种高效的排序算法,通过递归分解数组,将较小的元素移到左侧,较大的元素移到右侧,然后对左右两个子数组进行快速排序。
function quickSort(arr, left, right) {
if (left < right) {
const pivotIndex = partition(arr, left, right);
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
function partition(arr, left, right) {
const pivot = arr[right];
let i = left - 1;
for (let j = left; j < right; j++) {
if (arr[j] < pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];
return i + 1;
}
const arr = [5, 2, 9, 1, 5, 6];
const sortedArr = quickSort(arr, 0, arr.length - 1);
console.log(sortedArr); // [1, 2, 5, 5, 6, 9]
- 链表操作 JavaScript中没有链表的语法,但可以使用对象来模拟链表。以下是一个简单的链表操作示例。
function Node(value) {
this.value = value;
this.next = null;
}
function LinkedList() {
this.head =