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。
具体解析详见红宝书