数组算法排序实现

重写 Array.filter()

复制代码
javascript复制代码Array.prototype.myFilter = function(callback, thisArg) {
    const result = [];
    for (let i = 0; i < this.length; i++) {
        if (callback.call(thisArg, this[i], i, this)) {
            result.push(this[i]);
        }
    }
    return result;
};
​
// 测试
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.myFilter(num => num > 2);
console.log(filteredArr); // [3, 4, 5]

算法1:合并两个已排序的数组

复制代码
javascript复制代码function mergeSortedArrays(arr1, arr2) {
    let i = 0, j = 0;
    const result = [];
​
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) {
            result.push(arr1[i]);
            i++;
        } else {
            result.push(arr2[j]);
            j++;
        }
    }
​
    // 处理剩余元素
    return result.concat(arr1.slice(i)).concat(arr2.slice(j));
}
​
// 测试
const arr1 = [1, 3, 5, 7];
const arr2 = [2, 4, 6, 8];
console.log(mergeSortedArrays(arr1, arr2)); // [1, 2, 3, 4, 5, 6, 7, 8]

算法2:数值序列化(每隔三位一个逗号)

复制代码
javascript复制代码function numberWithCommas(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
​
// 测试
const num = 1234567890;
console.log(numberWithCommas(num)); // 1,234,567,890

算法3:格式化 query 字符串

复制代码
javascript复制代码function parseQueryString(queryString) {
    const queryObj = {};
    const pairs = queryString.replace(/^\?/, '').split('&');
​
    for (const pair of pairs) {
        const [key, value] = pair.split('=');
        if (queryObj[key]) {
            if (Array.isArray(queryObj[key])) {
                queryObj[key].push(decodeURIComponent(value));
            } else {
                queryObj[key] = [queryObj[key], decodeURIComponent(value)];
            }
        } else {
            queryObj[key] = decodeURIComponent(value);
        }
    }
​
    return queryObj;
}
​
// 测试
const queryString = '?a=1&a=2&b=3';
console.log(parseQueryString(queryString)); // { a: ['1', '2'], b: '3' }
相关推荐
再学一点就睡1 天前
前端网络实战手册:15个高频工作场景全解析
前端·网络协议
NAGNIP1 天前
一文搞懂树模型与集成模型
算法·面试
NAGNIP1 天前
万字长文!一文搞懂监督学习中的分类模型!
算法·面试
技术狂人1681 天前
工业大模型工程化部署实战!4 卡 L40S 高可用集群(动态资源调度 + 监控告警 + 国产化适配)
人工智能·算法·面试·职场和发展·vllm
D_FW1 天前
数据结构第六章:图
数据结构·算法
C_心欲无痕1 天前
有限状态机在前端中的应用
前端·状态模式
C_心欲无痕1 天前
前端基于 IntersectionObserver 更流畅的懒加载实现
前端
candyTong1 天前
深入解析:AI 智能体(Agent)是如何解决问题的?
前端·agent·ai编程
柳杉1 天前
建议收藏 | 2026年AI工具封神榜:从Sora到混元3D,生产力彻底爆发
前端·人工智能·后端
weixin_462446231 天前
使用 Puppeteer 设置 Cookies 并实现自动化分页操作:前端实战教程
运维·前端·自动化