前端算法面试题汇总

数组去重

function unique(arr) {
    const seen=new Map();
    return arr.filter((a) => !seen.has(a)&& seen.set(a,1));
}
//or
function unique(arr) {
    return Array.from(new Set(arr))
}
//or
[...(new Set(arr))];

求mul(1)(2)(3),其中调用次数未限定

单调用三次

var mul = function(a){
    return function(b){
        return function(c){
            return a*b*c;
        };
    };
};
function mul(x) {
    var product= x;
    var tmp = function (y) {
        product = product * y;
        return tmp;
    };
    tmp.toString = function () {
        return product ;
    };
    return tmp;
}
console.log(mul(1)(2)(3));  //6
console.log(mul(1)(2)(3)(4));   //24

查找两个节点的最近公共父节点

function commonParentNode(oNode1,oNode2) {
    var nodes1=[],nodes2=[];
    while (oNode1){
        nodes1.push(oNode1);
        oNode1=oNode1.parentNode;
    }
    while (oNode2){
        nodes2.push(oNode2);
        oNode2=oNode2.parentNode;
    }
    while (( a = nodes1.pop()) === nodes2.pop()){
        node = a;
    }
    return node;
}
function commonParentNode(oNode1,oNode2) {
    if(!oNode1||!oNode2){
        return null;
    }
    for(;oNode1;oNode1=oNode1.parentNode){
        if(oNode1.contains(oNode2)){
            return oNode1;
        }
    }
}

求1000以内的质数

function prime(n) {
    var arr=[];
    for(var i=2;ifor(var j=2;j<Math.sqrt(i);j++){
            if(i%j===0){
                break;
            }
        }
        if(j>=Math.sqrt(i)){
            arr.push(i);
        }
    }
    return arr;
}

你可能感兴趣的:(数据结构和算法)