news 2026/7/12 10:42:11

JavaScript常用算法深度解析:从浏览器到Node.js的实战

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
JavaScript常用算法深度解析:从浏览器到Node.js的实战

目录

一、JavaScript算法设计的现代范式

1.1 JavaScript算法的演进革命

1.2 JavaScript算法的独特优势

二、数组与对象算法

2.1 现代数组操作方法

2.2 迭代器与生成器算法

三、排序与搜索算法

3.1 现代排序技术

3.2 高效搜索算法

四、性能优化与内存管理

4.1 算法性能优化技巧

4.2 数据缓存与记忆化

五、实用算法与设计模式

5.1 函数式编程实用算法

5.2 实用数据处理算法


如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

一、JavaScript算法设计的现代范式

1.1 JavaScript算法的演进革命

JavaScript算法设计经历了三次重大变革:

  • ES5时代:函数式编程萌芽(map、filter、reduce)
  • ES6时代:箭头函数、解构、Promise、模块化
  • ES2020+时代:可选链、空值合并、BigInt、动态导入

1.2 JavaScript算法的独特优势

// 1. 函数式编程的天然优势
const numbers = [1, 2, 3, 4, 5];

// 链式调用与组合
const result = numbers
.filter(n => n % 2 === 0) // [2, 4]
.map(n => n * 2) // [4, 8]
.reduce((sum, n) => sum + n, 0); // 12

// 2. 高阶函数与柯里化
const multiply = a => b => a * b;
const double = multiply(2);
const triple = multiply(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

// 3. 异步编程的优雅处理
async function processData(urls) {
const promises = urls.map(url => fetch(url).then(r => r.json()));
const results = await Promise.allSettled(promises);

return results
.filter(r => r.status === 'fulfilled')
.map(r => r.value);
}

二、数组与对象算法

2.1 现代数组操作方法

// 1. ES6+新增数组方法
const array = [1, 2, 3, 4, 5];

// find/findIndex - 查找元素
const firstEven = array.find(n => n % 2 === 0); // 2
const firstEvenIndex = array.findIndex(n => n % 2 === 0); // 1

// some/every - 条件检查
const hasEven = array.some(n => n % 2 === 0); // true
const allPositive = array.every(n => n > 0); // true

// flat/flatMap - 数组展平
const nested = [1, [2, [3, [4]]]];
const flattened = nested.flat(Infinity); // [1, 2, 3, 4]

const words = ["hello world", "good morning"];
const letters = words.flatMap(word => word.split(' '));
// ["hello", "world", "good", "morning"]

// 2. Array.from 与扩展运算符
// 类数组转数组
const nodeList = document.querySelectorAll('div');
const divArray = Array.from(nodeList);

// 创建范围数组
const range = (start, end) =>
Array.from({ length: end - start + 1 }, (_, i) => start + i);

console.log(range(1, 5)); // [1, 2, 3, 4, 5]

// 3. 使用Set和Map优化算法
// 数组去重
const duplicates = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(duplicates)]; // [1, 2, 3, 4, 5]

// 频率统计
function frequency(arr) {
return arr.reduce((map, item) => {
map.set(item, (map.get(item) || 0) + 1);
return map;
}, new Map());
}

// 4. 对象操作的高级技巧
// 对象合并与克隆
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };

// 浅合并
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 }

// 深克隆(简单版)
const deepClone = obj => JSON.parse(JSON.stringify(obj));

// 动态属性名(计算属性)
const dynamicKey = 'score';
const student = {
name: 'Alice',
[dynamicKey]: 95,
[`${dynamicKey}Level`]: 'A'
};

// 可选链与空值合并
const user = {
profile: {
address: {
city: 'New York'
}
}
};

const city = user?.profile?.address?.city ?? 'Unknown';
const score = user?.scores?.[0] ?? 0;

2.2 迭代器与生成器算法

// 1. 自定义迭代器
class Range {
constructor(start, end, step = 1) {
this.start = start;
this.end = end;
this.step = step;
}

[Symbol.iterator]() {
let current = this.start;
const end = this.end;
const step = this.step;

return {
next() {
if (current <= end) {
const value = current;
current += step;
return { value, done: false };
}
return { done: true };
}
};
}
}

// 使用
for (const num of new Range(1, 5)) {
console.log(num); // 1, 2, 3, 4, 5
}

// 2. 生成器函数
function* fibonacci(limit) {
let [prev, curr] = [0, 1];

while (curr <= limit) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}

// 惰性求值
const fibSequence = fibonacci(100);
console.log([...fibSequence]); // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

// 3. 异步生成器
async function* asyncGenerator(urls) {
for (const url of urls) {
const response = await fetch(url);
yield response.json();
}
}

// 使用for await...of
(async () => {
const urls = ['/api/data1', '/api/data2'];

for await (const data of asyncGenerator(urls)) {
console.log(data);
}
})();

三、排序与搜索算法

3.1 现代排序技术

// 1. 内置排序的灵活使用
const items = [
{ name: 'Apple', price: 3.5, rating: 4.2 },
{ name: 'Banana', price: 2.0, rating: 4.5 },
{ name: 'Cherry', price: 5.0, rating: 4.0 }
];

// 多字段排序
items.sort((a, b) => {
// 先按价格升序,再按评分降序
if (a.price !== b.price) {
return a.price - b.price;
}
return b.rating - a.rating;
});

// 2. 稳定排序的实现
function stableSort(array, compare) {
return array
.map((item, index) => ({ item, index }))
.sort((a, b) => {
const result = compare(a.item, b.item);
return result === 0 ? a.index - b.index : result;
})
.map(({ item }) => item);
}

// 3. 使用Intl.Collator进行本地化排序
const germanWords = ['ä', 'z', 'a'];
germanWords.sort(new Intl.Collator('de').compare);
// ['a', 'ä', 'z']

// 4. 快速排序(函数式版本)
const quickSort = arr => {
if (arr.length <= 1) return arr;

const pivot = arr[0];
const left = arr.slice(1).filter(x => x <= pivot);
const right = arr.slice(1).filter(x => x > pivot);

return [...quickSort(left), pivot, ...quickSort(right)];
};

3.2 高效搜索算法

// 1. 二分查找(支持复杂比较)
function binarySearch(arr, target, compareFn = (a, b) => a - b) {
let left = 0;
let right = arr.length - 1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
const cmp = compareFn(arr[mid], target);

if (cmp === 0) return mid;
if (cmp < 0) left = mid + 1;
else right = mid - 1;
}

return -1;
}

// 2. 使用Map实现O(1)查找
class FastLookup {
constructor(items, keyFn = item => item.id) {
this.map = new Map();
this.keyFn = keyFn;

items.forEach(item => {
this.map.set(keyFn(item), item);
});
}

get(key) {
return this.map.get(key);
}

has(key) {
return this.map.has(key);
}
}

// 3. 模糊搜索(Levenshtein距离)
function levenshteinDistance(a, b) {
const matrix = Array(b.length + 1)
.fill()
.map(() => Array(a.length + 1).fill(0));

for (let i = 0; i <= a.length; i++) matrix[0][i] = i;
for (let j = 0; j <= b.length; j++) matrix[j][0] = j;

for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[j][i] = Math.min(
matrix[j][i - 1] + 1, // 删除
matrix[j - 1][i] + 1, // 插入
matrix[j - 1][i - 1] + cost // 替换
);
}
}

return matrix[b.length][a.length];
}

// 4. 使用Trie树进行前缀搜索
class TrieNode {
constructor() {
this.children = new Map();
this.isEndOfWord = false;
}
}

class Trie {
constructor() {
this.root = new TrieNode();
}

insert(word) {
let node = this.root;

for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char);
}

node.isEndOfWord = true;
}

search(prefix) {
let node = this.root;

// 找到前缀的最后一个节点
for (const char of prefix) {
if (!node.children.has(char)) {
return [];
}
node = node.children.get(char);
}

// 收集所有以该前缀开头的单词
return this._collectWords(node, prefix);
}

_collectWords(node, prefix) {
const words = [];

if (node.isEndOfWord) {
words.push(prefix);
}

for (const [char, childNode] of node.children) {
words.push(...this._collectWords(childNode, prefix + char));
}

return words;
}
}

四、性能优化与内存管理

4.1 算法性能优化技巧

// 1. 使用Web Workers进行CPU密集型计算
// main.js
const worker = new Worker('worker.js');

worker.postMessage({ data: largeArray });
worker.onmessage = event => {
console.log('Result:', event.data);
};

// worker.js
self.onmessage = event => {
const result = heavyComputation(event.data.data);
self.postMessage(result);
};

// 2. 使用requestIdleCallback进行调度
function processInBackground(tasks) {
function processTask(deadline) {
while (tasks.length > 0 && deadline.timeRemaining() > 0) {
const task = tasks.shift();
executeTask(task);
}

if (tasks.length > 0) {
requestIdleCallback(processTask);
}
}

requestIdleCallback(processTask);
}

// 3. 使用WeakMap和WeakSet优化内存
// WeakMap的键是弱引用,不影响垃圾回收
const weakCache = new WeakMap();

function expensiveComputation(obj) {
if (weakCache.has(obj)) {
return weakCache.get(obj);
}

const result = /* 复杂计算 */;
weakCache.set(obj, result);
return result;
}

// 4. 防抖与节流优化
function debounce(fn, delay) {
let timer;

return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}

function throttle(fn, limit) {
let inThrottle;

return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}

// 5. 使用位运算优化
// 判断奇偶
const isEven = n => (n & 1) === 0;

// 交换两个数(不使用临时变量)
let a = 5, b = 10;
a ^= b;
b ^= a;
a ^= b;

// 判断2的幂
const isPowerOfTwo = n => n > 0 && (n & (n - 1)) === 0;

4.2 数据缓存与记忆化

// 1. 记忆化函数(Memoization)
function memoize(fn) {
const cache = new Map();

return function(...args) {
const key = JSON.stringify(args);

if (cache.has(key)) {
return cache.get(key);
}

const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}

// 使用
const factorial = memoize(n => {
if (n <= 1) return 1;
return n * factorial(n - 1);
});

// 2. LRU缓存实现
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}

get(key) {
if (!this.cache.has(key)) return -1;

// 移动到最新位置
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);

return value;
}

put(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// 删除最旧的项
const oldestKey = this.cache.keys().next().value;
this.cache.delete(oldestKey);
}

this.cache.set(key, value);
}
}

// 3. 使用Proxy实现智能缓存
function createCachedApi(apiFunction) {
const cache = new Map();

return new Proxy(apiFunction, {
apply(target, thisArg, args) {
const key = JSON.stringify(args);

if (cache.has(key)) {
console.log('Cache hit:', key);
return Promise.resolve(cache.get(key));
}

return target.apply(thisArg, args).then(result => {
cache.set(key, result);
return result;
});
}
});
}

五、实用算法与设计模式

5.1 函数式编程实用算法

// 1. 函数组合与管道
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);

// 使用
const add = x => y => x + y;
const multiply = x => y => x * y;
const square = x => x * x;

const compute = pipe(
add(5), // x + 5
multiply(2), // (x+5)*2
square // ((x+5)*2)^2
);

console.log(compute(3)); // ((3+5)*2)^2 = 256

// 2. 柯里化工具函数
const curry = fn => {
const arity = fn.length;

return function curried(...args) {
if (args.length >= arity) {
return fn.apply(this, args);
} else {
return (...moreArgs) => curried.apply(this, args.concat(moreArgs));
}
};
};

// 使用柯里化
const sum = curry((a, b, c) => a + b + c);
const add5 = sum(5);
const add5And10 = add5(10);

console.log(add5And10(15)); // 30

// 3. 惰性求值与无限序列
function* naturalNumbers() {
let n = 1;
while (true) {
yield n++;
}
}

// 获取前10个偶数
const first10Evens = [...naturalNumbers()]
.filter(n => n % 2 === 0)
.slice(0, 10);

// 4. Transducer(转换器)模式
const mapTransducer = fn => next => (acc, val) => next(acc, fn(val));
const filterTransducer = predicate => next => (acc, val) =>
predicate(val) ? next(acc, val) : acc;

const transduce = (transducer, reducer, initial, collection) => {
const transform = transducer(reducer);
return collection.reduce(transform, initial);
};

// 使用
const numbers = [1, 2, 3, 4, 5];
const xform = compose(
mapTransducer(x => x * 2),
filterTransducer(x => x > 5)
);

const result = transduce(xform, (acc, val) => [...acc, val], [], numbers);
// [6, 8, 10]

5.2 实用数据处理算法

// 1. 数据分组与聚合
function groupBy(array, keyFn) {
return array.reduce((groups, item) => {
const key = keyFn(item);
if (!groups[key]) groups[key] = [];
groups[key].push(item);
return groups;
}, {});
}

// 使用
const students = [
{ name: 'Alice', grade: 'A', subject: 'Math' },
{ name: 'Bob', grade: 'B', subject: 'Math' },
{ name: 'Charlie', grade: 'A', subject: 'Science' }
];

const bySubject = groupBy(students, s => s.subject);

// 2. 数据采样与分页
function paginate(array, pageSize, pageNumber) {
const start = (pageNumber - 1) * pageSize;
const end = start + pageSize;
return array.slice(start, end);
}

function reservoirSampling(array, k) {
const sample = array.slice(0, k);

for (let i = k; i < array.length; i++) {
const j = Math.floor(Math.random() * (i + 1));
if (j < k) {
sample[j] = array[i];
}
}

return sample;
}

// 3. 数据验证与清洗
const validators = {
required: value => value != null && value.toString().trim() !== '',
email: value => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
minLength: min => value => value.length >= min,
maxLength: max => value => value.length <= max,
pattern: regex => value => regex.test(value)
};

function validate(data, rules) {
const errors = {};

for (const [field, fieldRules] of Object.entries(rules)) {
for (const rule of fieldRules) {
if (!rule.validator(data[field])) {
errors[field] = rule.message;
break;
}
}
}

return errors;
}

// 4. 数据转换管道
class DataPipeline {
constructor() {
this.steps = [];
}

addStep(fn) {
this.steps.push(fn);
return this;
}

process(data) {
return this.steps.reduce((acc, step) => step(acc), data);
}
}

// 使用
const pipeline = new DataPipeline()
.addStep(data => data.filter(item => item.active))
.addStep(data => data.map(item => ({
...item,
score: item.points * item.multiplier
})))
.addStep(data => data.sort((a, b) => b.score - a.score))
.addStep(data => data.slice(0, 10));

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/6 0:49:39

企业OA系统安全防护全攻略:从基础加固到长效防御,十分钟构建坚不可摧的办公安全屏障

OA系统作为企业数字化办公的核心中枢&#xff0c;承载着员工信息、财务数据、业务流程、商业机密等关键资产&#xff0c;是企业生产经营的“神经中枢”。随着数字化办公的深度普及&#xff0c;OA系统已成为网络攻击的重点目标——从弱密码爆破、漏洞利用到钓鱼攻击、内部泄密&a…

作者头像 李华
网站建设 2026/7/2 4:23:31

数字取证之浏览器取证:技术体系、实操方法与实战要点

浏览器作为用户网络行为的核心载体&#xff0c;记录了访问轨迹、数据交互、账户信息、文件操作等全维度行为痕迹&#xff0c;是数字取证中电子数据固定与分析的核心环节&#xff0c;广泛应用于网络犯罪调查、民事纠纷取证、企业合规审计等场景。浏览器取证的核心目标是无篡改提…

作者头像 李华
网站建设 2026/7/11 15:01:12

MaaP:5G短消息的“心脏引擎”,政企招标暗藏的决胜密码!

作者&#xff1a;尘客首发&#xff1a;5G全域通每一条消息都是奇迹的发生。3.4亿&#xff01;中国移动三期工程、3.27亿&#xff01;中国电信全国升级——所有5G消息招标文件里&#xff0c;藏着同一个关键词&#xff1a; MaaP读懂它&#xff0c;中标率提升50%&#xff1b;忽略它…

作者头像 李华
网站建设 2026/7/5 20:39:16

专科生必备8个降AI率工具,高效避坑指南!

专科生必备8个降AI率工具&#xff0c;高效避坑指南&#xff01; AI降重工具&#xff1a;专科生论文的“隐形助手” 在当前高校教育日益重视学术规范的大背景下&#xff0c;越来越多的专科生开始关注论文的AIGC率和查重率问题。尤其是随着AI写作工具的普及&#xff0c;许多学生…

作者头像 李华
网站建设 2026/6/26 11:28:48

【读书笔记】《光环效应》

《光环效应》读书笔记 核心观点 《光环效应》揭示了一个残酷的事实&#xff1a;过去许多奉为经典的商业书籍&#xff0c;其实都只是人们的主观总结和猜测&#xff0c;因为它们全部被"光环效应"所笼罩。 什么是光环效应? 经典案例&#xff1a;乐高 vs 711 乐高的…

作者头像 李华
网站建设 2026/7/8 2:01:20

AI日报 - 2026年01月27日

#本文由AI生成 &#x1f310; 一、【行业深度】 1. &#x1f9e7; 腾讯元宝双重磅落地&#xff0c;春节派10亿现金红包上线混元图像3.0 &#x1f525; 热点聚焦&#xff1a; 1月25-26日腾讯元宝接连释放两大动作&#xff0c;先是官宣2月1日开启新春10亿现金红包活动&#xff0c…

作者头像 李华