前端面试100题随笔

function fib1(max) {
let a = 0;
let b = 1;
let arr = [0,1];
while (arr.length <max){
[a, b] = [b, a + b];
arr.push(b);
}
console.log(arr)
}

fib1(10);

function deepCopy(obj) {

let result = Array.isArray(obj)?[]:{};
if(obj&&typeof obj === "object"){
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(obj[key] && typeof obj[key] === obj){
                result[key] = deepCopy(obj[key])
            }else{
                result[key] = obj[key]
            }
        }
    }
}
return result;

}

//防抖
function debounce(fn, delay) {
let timer = null;
let _this = this;
return function () {
clearTimeout(timer);
timer = setTimeout(()=>{
fn.apply(_this,arguments);
},delay);
};
}

function sayHi() {
console.log(‘防抖’);
}

var inp = document.getElementById(‘inp’);
inp.addEventListener(“scalll”,debounce(sayHi,500));

//节流
function throttle(fn,delay) {
let canrun = true;
let _this = this;
return function () {
if(!canrun)return;
canrun = false;
setTimeout(()=>{
fn.apply(_this,arguments);
canrun = true;
},delay)
}
}

//es6 使用set去重
let arr2 = [1,2,3,4,5,2,3,3];
let newArr1 = […new Set(arr2)];

//取交集 这个方法是不行滴,循环逻辑有问题,遍循环遍删 不行的
function jiaoji2(arr1,arr2) {
let resultArr = [];
for(let i in arr1){
for (let j in arr2){
if(arr1[i]===arr2[j]){
console.log(i,j);
let item = arr1.splice(i,1);
console.log(arr1);
arr2.splice(j,1);
console.log(arr2);
resultArr.push(item);
}
}
}
return resultArr;
}

var newArr = arr1.filter(function (x) {
arr2.indexOf(x)>-1
})

let ret =[];
let j = 0;
let temp= arr2[0];
for(let i in arr1){
if(arr2[j] == arr1[i].charAt(0)){
ret.push(arr1[i])
}else{
ret.push(temp);
ret.push(arr1[i]);
temp=arr2[++j];
}
if(i == (arr1.length -1)){
ret.push(temp)
}
}
console.log(ret);

//继承、实例方法

function A() {

}

//静态方法
A.sayhello = function (){
console.log(‘hello’);
};

A.sayhello();

//实例方法
A.prototype.sayHi = function () {
console.log(‘hi’);
};
let a = new A();
a.sayHi();

function B() {

};

//继承
B.prototype = new A();

let b= new B();
b.sayHi();

//工具函数
//重写 toString()和Object.prototype.toString()的不同,https://blog.csdn.net/shi_1204/article/details/79741220
let getEmpty = function (origin) {
if(Object.prototype.toString.call(origin) === ‘[object Object]’){
return {};
}
if(Object.prototype.toString.call(origin) === ‘[object Array]’){
return [];
}

return origin;

};

//广度优先拷贝
function deepCopyBFS(origin){
let queue = [];//用队列 先进先出
let map = new Map();//用于记录出现过的对象,用于处理环
let target = getEmpty(origin);
if(target !== origin){
queue.push([origin,target]);
map.set(origin,target);
}

while (queue.length) {
    let [ori,tar] = queue.shift();//对象赋值,是指针引用
    for(let key in ori){
        if(map.get(ori[key])){//处理环状
            tar[key] = map.get(tar[key]);
            continue;
        }

        tar[key] = getEmpty(ori[key]);
        if(tar[key] !== ori[key]){
            queue.push([ori[key],tar[key]]);
            map.set(ori[key],tar[key]);
        }
    }
}

return target;

}

//深度优先拷贝

function deepCopyDFS(origin){
let stack = [];//用队列 先进先出
let map = new Map();//用于记录出现过的对象,用于处理环
let target = getEmpty(origin);
if(target !== origin){
stack.push([origin,target]);
map.set(origin,target);
}

while (stack.length) {
    let [ori,tar] = stack.pop();//对象赋值,是指针引用
    for(let key in ori){
        if(map.get(ori[key])){//处理环状
            tar[key] = map.get(tar[key]);
            continue;
        }

        tar[key] = getEmpty(ori[key]);
        if(tar[key] !== ori[key]){
            stack.push([ori[key],tar[key]]);
            map.set(ori[key],tar[key]);
        }
    }
}

return target;

}

// test
[deepCopyBFS, deepCopyDFS].forEach(deepCopy=>{
console.log(deepCopy({a:1}));
console.log(deepCopy([1,2,{a:[3,4]}]))
console.log(deepCopy(function(){return 1;}))
console.log(deepCopy({
x:function(){
return “x”;
},
val:3,
arr: [
1,
{test:1}
]
}))

let circle = {};
circle.child = circle;
console.log(deepCopy(circle));

})

function test2(arr1,arr2) {
let result = [];
let j = 0;
let temp = arr2[0];
for(let i in arr1){
if(temp === arr1[i].substring(0,1)){
result.push(arr1[i]);
}else{
result.push(temp);
temp = arr2[++j];
result.push(arr1[i]);
}
if(i == (arr1.length -1)){
result.push(temp);
}
}
return result;
}

for (var i = 0; i< 10; i++){
(function (i){setTimeout(() => {
console.log(i);
}, 1000)})(i)
}

//flatten函数,展平,递归方式实现
var arr=[1,2,3,[4,5],[6,[7,[8]]]];

function flatten1(arr) {
let result = [];
for(let item of arr){
console.log(‘Array.isArray(item)’,Array.isArray(item));
if(Array.isArray(item)){
console.log(‘flatten(item)’,flatten1(item));
result.push(…flatten1(item));
console.log(‘result’,result);
}else{
result.push(item);
}
}
return result;
}
let aaa = flatten1(arr);

//flatten函数,展平,迭代方式实现,concat会把数组分解,

function flatten(arr) {
while (arr.some((item)=>Array.isArray(item))) {
arr = [].concat(…arr);
}
return arr;
};

var a ={
i : 1,
toString:function () {
return a.i++;
}
};

//42题,实现sleep(1000)

//Promise
const sleep = time =>{
return new Promise(resolve => setTimeout(resolve,time))
};

sleep(1000).then(()=>{console.log(1)});

//Generator
function* sleepGenerator(time) {
yield new Promise(function (resolve, reject) {
setTimeout(resolve,time)
})
}

sleepGenerator(1000).next().value.then(()=>{console.log(1)});

//async
function sleepAsync() {
return new Promise((resolve => setTimeout(resolve,1000)))
}

async function output() {
await sleepAsync(1000);
console.log(1);
}

output();

//es5
function sleepEs5(callback,time) {
if(typeof callback ===‘function’){
setTimeout(callback,time)
}
}

function calllback() {
console.log(1)
}

sleepEs5(calllback,1000);

//第55题
let obj1 = {1:222, 2:123, 5:888};

function change() {
let arr = Array.from({length:12});
for(let index in arr){
console.log(Number(index)+1,obj1[Number(index)+1]);

    if(obj1[Number(index)+1]){
        arr[index] = obj1[Number(index)+1];
    }else{
        arr[index] = null;
    }
}
return arr;

}

let arrchanged = change();
console.log(‘arrchanged’,arrchanged);

const result = Array.from({length:12}).map((_,index)=>obj1[index+1]||null);

let string = ‘aBc’;
//67题
let newString = ‘’;
for (let item of string){
if(item ==item.toLowerCase()){
newString+=item.toUpperCase();
}else{
newString+=item.toLowerCase();
}
}

console.log(newString);

//71
let find = (s,t)=>{
if(s.length<t.length) return -1;
for(let i = 0 ;i<s.length-t.length;i++){
if(s.substr(i,t.length) == t){
return i;
}
}
return -1;
};

//82,slice不改变原数组,splice改变原数组
let arr82 = [0,1,0,3,12];
function move(arr) {
let j = 0;
let len = arr.length;
for(let i = 0;i<len -j;i++){
if(arr[i] ===0){
arr.push(0);
arr.splice(i,1);
i–;
j++;
}
}
return arr;
}

move(arr82);

//88题.再研究

// 原始 list 如下
let list =[
{id:1,name:‘部门A’,parentId:0},
{id:2,name:‘部门B’,parentId:0},
{id:3,name:‘部门C’,parentId:1},
{id:4,name:‘部门D’,parentId:1},
{id:5,name:‘部门E’,parentId:2},
{id:6,name:‘部门F’,parentId:3},
{id:7,name:‘部门G’,parentId:2},
{id:8,name:‘部门H’,parentId:4}
];
function convert(list) {
const res = []
const map = list.reduce((res, v) => (res[v.id] = v, res), {});
console.log(‘map’,map);
for (const item of list) {
if (item.parentId === 0) {
res.push(item);
continue
}
if (item.parentId in map) {
console.log(‘map[item.parentId]’,map[item.parentId]);
const parent = map[item.parentId]
console.log(‘parent’,parent,‘parent.children’,parent.children);
parent.children = parent.children || []
parent.children.push(item)
}
}
return res
}

convert(list);

//92

const data = [{
id: ‘1’,
name: ‘test1’,
children: [
{
id: ‘11’,
name: ‘test11’,
children: [
{
id: ‘111’,
name: ‘test111’
},
{
id: ‘112’,
name: ‘test112’
}
]

    },
    {
        id: '12',
        name: 'test12',
        children: [
            {
                id: '121',
                name: 'test121'
            },
            {
                id: '122',
                name: 'test122'
            }
        ]
    }
]

}];

function findParentsid(source,id,arr) {
for(let item of source){
console.log(‘item.id == id’,item.id == id);
arr.push(item.id);
if(item.id == id){
console.log(‘arr’,arr);
return arr;
}else{
console.log(‘arr’,arr);
arr = […arr];
if(item.children){
findParentsid(item.children,id,arr);
}
}
}
}

let arr92 =findParentsid(data,‘112’,[]);
console.log(‘arr92’,arr92);

function reverse(num) {
let num1 = num / 10;
let num2 = num % 10;
if(num1<1){
return num
}else{
let newNum = Math.floor(num1);
return ${num2}${reverse(newNum)}
}
}

reverse(1234);

//单例模式

class singleton {
constructor(){

}

}

singleton.getInstance = (function () {
let instance;
return function () {
if(!instance){
instance =new singleton()
}
return instance;
}
})(

);

let s1 = singleton.getInstance();
let s2 = singleton.getInstance();
console.log(s1 === s2);

//工厂模式
class Man {
constructor(name){
this.name = name
}

alertName(){
    alert(this.name)
}

}

class Factory {
static create(name){
return new Man(name)
}
}

Factory.create(‘shabi’).alertName();

//选择排序

function selectSort(arr) {
let resurt = [];
while(arr.length){
let min = 0;
for(let j in arr){
if(arr[min] >arr[j]){
min = j;
}
}
resurt.push(…arr.splice(min,1));
}
console.log(resurt);
return resurt;
}
let arr = [4,2,3,1,5];

selectSort(arr);

//冒泡排序

function bubbleSort(arr) {
let len = arr.length;
for(let i = 0;i<len-1;i++){
for(let j = 0;j<len - i -1;j++){
if(arr[j]>arr[j+1]){
[arr[j+1],arr[j]] = [arr[j],arr[j+1]];
}
}
}
return arr;
}

var arr=[1,3,5,12,14,8,99];
var result=bubbleSort(arr);
console.log(result); //[1, 3, 5, 8, 12, 14, 99]

//快速排序
function quickSort(arr) {
if(arr.length<2){
return arr
}else{
let base = arr[0];
let less = arr.filter((item)=>item<base);
let bigger = arr.filter((item)=>item>base);
return quickSort(less).concat([base].concat(quickSort(bigger)));
}
}
let arr = [4,2,3,1,5];

let result = quickSort(arr);
console.log(result);

//插入排序

function insertSort(arr) {
for(let i = 1;i<arr.length;i++){
let j = i - 1;
let temp = arr[i];
while (j>=0 && arr[j] > temp) {
arr[j+1] = arr[j];
j–;
}

    num[j+1] =temp;
}

}

let arr =[3,2,1,5 ];

let result = insertSort(arr);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值