前端JS基础面试题(nobook)

1.How would you remove duplicate members from an array?

let ary = [1, 2, 3, 4, 3, 2, 3, 5, 2, 3, 6];
function removeDuplicate(ary)  {

}
removeDuplicate(ary);

解题思路:根据题目可知这道题考点是数组去重。主要是3钟方法 es6 ,对象,遍历,判断。

//es6 Set去重
function removeDuplicate(ary) {
    return [...new Set(ary)]
}

// 借助于对象去重,增加map为了使数据的类型不改变
function removeDuplicate(ary) {
    var obj = {};
    ary.forEach(function (item) {
        obj[item] = item
    });
    return Object.keys(obj).map(function (key) {
        return obj[key]
    })
}

// 循环+判断。
function removeDuplicate(ary) {
    var result = [];
    ary.forEach(function (item) {
        if (result.indexOf(item) < 0) {
            result.push(item)
        }
    });
    return result
}

// 使用reduce函数
function removeDuplicate(ary) {
    return ary.reduce(function (result, cur) {
        if (result.indexOf(cur) < 0) {
            return result.concat(cur)
        }
        return result
    }, [])
}


2.How would you merge two sorted arrays?

let ary0 = [2, 3, 5, 5, 9, 20, 111, 323];
let ary1 = [1, 3, 6, 8, 22, 200];

function mergeSortedArray(a, b) {

}

mergeSortedArray(ary0, ary1);

这道题主要考的是合并两个升序的数组

// 拼接+排序。面试题期望的肯定不是这个解法
function mergeSortedArray(a, b) {
    return a.concat(b).sort(function (a, b) {
        return a - b
    })
}

// 先判断再拼接
function mergeSortedArray(a, b) {
    var result = [];
    var cursorA = 0;
    var cursorB = 0;
    while (a[cursorA] !== undefined || b[cursorB] !== undefined) {
        if (a[cursorA] > b[cursorB]) {
            result.push(b[cursorB]);
            cursorB++;
        } else {
            result.push(a[cursorA]);
            cursorA++
        }
    }
    return result
}

3. If you have a function which can generate random number between 1 to 5. How could you generate a random number 1 to 7 using the function?

function rand5() {
    return 1 + Math.random() * 4;
}

function rand7() {

}

将1-5的随机数改为1-7的随机数,这个没什么难度

function rand7() {
    return rand5() * 1.5 - 0.5
}

4.What will the code below output ? Explain your answer.

console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);

这道题结果为 0.30000000000000004 false。
具体解析详见红宝书

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,828评论 0 23
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,878评论 0 38
  • 五岁了 小马驹,今天你五岁了。爸爸,祝你生日快乐。 你特别在意你的生日,一直提醒给你过生日。前几天,和你同岁的婉儿...
    乡村追梦人阅读 241评论 0 4
  • 何人惹天公,白玉掩苍松。 飘零如变世,新尘没旧踪。
    北国又一春阅读 195评论 1 5