前端面試題彙總(待續)

【】插入排序

var arr = [1, 3, 2, 7, 4, 5, 6, 8, 7];
var current = null
var preIndex = null
var insertionSort = (arr) => {
    for (var i = 1; i < arr.length; i++){
        preIndex = i - 1;
        current = arr[i]
        while(preIndex >= 0 && current < arr[preIndex]) {
            arr[preIndex + 1] = arr[preIndex]
            preIndex --;
        }
        arr[preIndex + 1] = current
    }
    return arr
}
insertionSort(arr);

 

 

【】選擇排序

var arr = [1, 3, 2, 7, 4, 5, 6, 8, 7]
var index = null
var selectionSort = (arr) => {
    for (var i = 0; i < arr.length - 1; i++) {
        index = i;
        for (var j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[index]) {
                index = j
            }
        }
        var temp = arr[i]
        arr[i] = arr[index]
        arr[index] = temp
    }
    return arr;
}
selectionSort(arr)

 

 

【】冒泡排序

var arr = [1, 3, 2, 7, 4, 5, 6, 8]
var bubbleSort = (arr) => {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j+1] < arr[j]) {
                var temp = arr[j+1];
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
bubbleSort(arr)

 

 

【】es5實現const

const _const = (key, value) => {
     const desc = {        
        value,        
        writable: false    
    }    
    Object.defineProperty(window, key, desc)
}
_const('obj', {a: 1});
console.log(obj.a);
obj = {}; // Cannot redefine property: obj

 

 

【】es5實現let

(function() {
    for(var i = 0; i < 3; i++) {
        console.log(i);
    }
})();
console.log(i); // Uncaught ReferenceError: i is not defined

 

 

【】數組扁平化的幾種方式

1.es6的flat
var arr = [1,[2,3],[4,[5,6]],7];
console.log(arr.flat(Infinity));

2.序列化後正則
var arr = [1,[2,3],[4,[5,6]],7];
var str = `[${JSON.stringify(arr).replace(/\[|\]/g, '')}]`;
console.log(JSON.parse(str));

3.reduce遞歸
var arr = [1,[2,3],[4,[5,6]],7];
var flat = (arr) => {
  return arr.reduce((prev, cur) => {
    return prev.concat(cur instanceof Array ? flat(cur) : cur)
  }, [])
}
flat(arr);

4.遞歸
var arr = [1,[2,3],[4,[5,6]],7];
var flat = (arr) => {
  let result = []
  for (var item of arr) {
    item instanceof Array ? result = result.concat(flat(item)) : result.push(item)
  }
  return result
};
flat(arr);

5.迭代+展開運算符
var arr = [1,[2,3],[4,[5,6]],7];
while(arr.some(Array.isArray)){
    arr = [].concat(...arr);
}
console.log(arr)

 

【】函數柯里化

概念:柯里化是一個函數轉換的過程,是指把接收多個參數的函數變換成接收單一參數的函數,嵌套返回直到所有參數都被使用並返回最終結果。將fn(a,b,c)轉爲fn(a)(b)(c),它不會調用函數。

function addThreeNum (a, b, c) {
    return a + b + c;
}
addTreeNum(6, 9 ,10);// 返回結果爲25
------------------

function addhTreeNumCurry(a) {
    return function(b) {
        return function(c) {
            return a + b + c;
        }
    }
}
addThreeNumCurry(6)(9)(10);// 返回結果同樣是25

// 分部調用柯里化後的函數
const add1 = addThreeNumCurry(6);// 返回的是一個函數
const add2 = add1(9);// 返回的是一個函數
const add3 = add2(10);// 已接收到所有的參數,返回最終的計算結果

console.log(add3);// 25

 

【】ES6的extends繼承

class A {
    constructor() {
        this.name = 'A';
    }
    getName() {
        return this.name;
    }
}

class B extends A {
    constructor() {
        super();

        this.name = 'B';
    }
}

let bIn = new B();
console.log(bIn.getName())

 

 

【】原型鏈繼承

function A(aName) {
    this.aName = aName;
    this.sayA = function() {
        console.log(this.aName);
    };
    
}
A.prototype.age = 10;
function B() {}
B.prototype = new A('bName');
var test = new B();
console.log(test.sayA())

 


【】原型式繼承

function A(aName) {
    this.aName = aName;
    this.sayA = function() {
        console.log(this.aName);
    };
    
}
A.prototype.age = 10;
function sup(obj) {
    function F() {} 
    F.prototype = obj;
    return new F();
}
var test1 = new A('test');
var test2 = sup(test1);
console.log(test1.sayA())
console.log(test2.sayA())

 


【】構造函數繼承

function A(aName) {
    this.aName = aName;
    this.sayA = function() {
        console.log(this.aName);
    };
    
}
A.prototype.age = 10;
function B() {
    A.call(this, 'bName')
}
var test = new B();
console.log(test.sayA())

 


【】組合繼承

function A(aName) {
    this.aName = aName;
    this.sayA = function() {
        console.log(this.aName);
    };
    
}
A.prototype.age = 10;
function B(aName) {
    A.call(this, aName)
}
B.prototype = new A();
var test = new B('testName');
console.log(test.sayA())

 

【】寄生式繼承

function A(aName) {
    this.aName = aName;
    this.sayA = function() {
        console.log(this.aName);
    };
    
}
A.prototype.age = 10;

function sup(obj) {
    function F() {}
    F.prototype = obj;
    return new F();
}

function supN(obj) {
    var supN = sup(obj);
    supN.newAge = 20;
    return supN;
}


var aIn = new A('aIn');
var bIn = supN(aIn);
console.log(aIn.age)
console.log(aIn.newAge)
console.log(bIn.newAge)

 

【】寄生組合式繼承

function A(aName) {
    this.aName = aName;
    this.sayA = function() {
        console.log(this.aName);
    };
    
}
A.prototype.age = 10;

function sup(obj) {
    function F() {}
    F.prototype = obj;
    return new F();
}
var temp = sup(A.prototype);

function B(name) {
    A.call(this, name);
}
B.prototype = temp;


var test1 = new B('test1');

console.log(test1.sayA())
console.log(temp)

 

【】JS解決異步的方法有哪些

1.回調函數
2.事件監聽
3.發佈-訂閱
4.Promise
5.Generator
6.Async/Await
7.yield

 

【】JS有幾種數據類型

1.null
2.undefined
3.boolean
4.number
5.string
6.symbol
7.bigInt
9.array
10.object
11.function

 

【】獲取DOM裏所有標籤

new Set([...document.querySelectorAll('*')].map(e => e.tagName))

 

【】對象的深淺拷貝

var obj = {
    a: null,
    b: undefined,
    c: function() {
        console.log('c');
    },
    d: 'd_value',
    e: {
        e1: null,
        e2: undefined,
        e3: function() {
            console.log('e3');
        },
        e4: 'e4_value',
        e5: {
            e51: null,
            e52: undefined,
            e53: function() {
                console.log('e53');
            },
            e54: 'e54'
        }
    }
}



1.JSON.parse(JSON.stringify(obj))
缺點:不可以拷貝一些特殊的屬性(例如正則表達式,undefine,function)
var obj_clone = JSON.parse(JSON.stringify(obj));
console.log(obj_clone)

2.遞歸
var deepClone = (obj) => {
    if (toString.call(obj).search('Object') === -1) {
        return;
    } 
    let obj_clone = toString.call(obj).search('Object') !== -1 ? {} : [];
    for (var key in obj) {
        if (obj[key] && toString.call(obj[key]).search('Object') !== -1) {
            obj_clone[key] = deepClone(obj[key]);
        } else {
            obj_clone[key] = obj[key];
        }
    }
    return obj_clone;
}
var obj_clone = deepClone(obj);
console.log(obj_clone);

3.用Object.assign。
當對象中只有一級屬性,沒有二級屬性的時候,此方法爲深拷貝,但是對象中有對象的時候,此方法,在二級屬性以後就是淺拷貝。
var obj_clone = Object.assign(obj);
console.log(obj_clone);

 

【】判斷數據類型的幾種方式

console.log(typeof 1);               // number
console.log(typeof true);            // boolean
console.log(typeof 'mc');           // string
console.log(typeof function(){});    // function
console.log(typeof []);              // object
console.log(typeof {});              // object
console.log(typeof null);            // object
console.log(typeof undefined);       // undefined
優點:能夠快速區分基本數據類型 缺點:不能將Object、Array和Null區分,都返回object。
原理:不同的對象在底層都表示爲二進制,在Javascript中二進制前(低)三位存儲其類型信息。
000: 對象
010: 浮點數
100:字符串
110: 布爾
1: 整數

console.log(1 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false  
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true
優點:能夠區分Array、Object和Function,適合用於判斷自定義的類實例對象 缺點:Number,Boolean,String基本數據類型不能判斷
原理: 檢測 constructor.prototype是否存在於參數 object的 原型鏈上。
object instanceof constructor 等同於 constructor.prototype.isPrototypeOf(object)


var toString = Object.prototype.toString;
console.log(toString.call(1));                      //[object Number]
console.log(toString.call(true));                   //[object Boolean]
console.log(toString.call('mc'));                  //[object String]
console.log(toString.call([]));                     //[object Array]
console.log(toString.call({}));                     //[object Object]
console.log(toString.call(function(){}));           //[object Function]
console.log(toString.call(undefined));              //[object Undefined]
console.log(toString.call(null));                   //[object Null]
優點:精準判斷數據類型 缺點:寫法繁瑣不容易記,推薦進行封裝後使用

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章