前端面試之你可能會遇到的編程題(1)

Github - program-learning-listsjavascript

知乎前端

我的博客java

Githubgit


「開源(open source)」這個詞,指的是事物規劃爲能夠公開訪問的,所以人們能夠修改並分享。github

做爲一個從大型同性社交網站GitHub / Rain120上學習成長的一個前端菜鳥的我,深受大佬的感染,也但願有機會可以給一樣是菜鳥的大家提供幫助,在我學習之餘,留下了以前學習遇到的、網上看到的、筆試面試遇到的一些編程的解法,還請各位大佬手下留情,多多提攜、指點我等菜鳥。面試

歡迎各位大佬留下更加簡單的寫法,謝謝!!編程

抱大腿

代碼倉庫: Web-Study數組

廢話很少說,先上題吧。網絡

一、關係型數組轉換成樹形結構對象(拼多多2018前端筆試真題 / 依圖面試)

關係型數組函數

var obj = [
    { id:3, parent:2 },
    { id:1, parent:null },
    { id:2, parent:1 },
]

指望結果:

o = {
  obj: {
    id: 1,
    parent: null,
    child: {
      id: 2,
      parent: 1,
      child: {
          id: ,3,
          parent: 2
      }
    }
  }
}

思路:

先找到它的根元素,根據idparent來判斷它們之間的關係

實現源碼:

function treeObj(obj) {
  obj.map(item => {
    if (item.parent !== null) {
      obj.map(o => {
        if (item.parent === o.id) {
          if (!o.child) {
            o.child = [];
          }
          o.child.push(item);
          o.child = o.child;
        }
      });
    }
  });
  return obj.filter(item => item.parent === null)[0]
}

解法2:(知乎評論區提供的方法)

function treeObj(obj) {
  return obj.sort((a, b) => b.parent - a.parent)
      .reduce((acc, cur) => (acc ? { ...cur, child: acc } : cur));
}

實現效果:
第一題實現效果

二、請用 javascript 實現一個函數 parseUrl(url),將一段 url字符串解析爲 Object。(西洋匯筆試)

parseUrl("http://www.xiyanghui.com/product/list?id=123456&sort=discount#title");

指望結果:

{
    protocol: "http",
    host: "www.xiyanghui.com",
    path: "/product/list",
    params: {
        id: "12345",
        sort: "discount"
    },
    hash: "title"
}

思路:

首先咱們須要瞭解一下URL這個概念。

URL(統一資源定位符)(或稱統一資源定位器/定位地址、URL地址等,英語:Uniform Resource Locator,常縮寫爲URL),有時也被俗稱爲網頁地址(網址)。

這裏,我補充一點,各位不只須要瞭解 URL,還須要瞭解 URI

URI:統一資源標識符(英語:Uniform Resource Identifier,或URI)是一個用於標識某一互聯網資源名稱的字符串。 該種標識容許用戶對網絡中(通常指萬維網)的資源經過特定的協議進行交互操做。URI的最多見的形式是統一資源定位符(URL),常常指定爲非正式的網址。更罕見的用法是統一資源名稱(URN),其目的是經過提供一種途徑。用於在特定的名字空間資源的標識,以補充網址。

URI包括了URLURN
URI

下圖展現了兩個 URI 例子及它們的組成部分。
URI 例子及它們的組成部分

URL通常包括協議域名端口queryparams等,咱們在傳入參數時是字符串,咱們須要將它轉換成URL,能夠經過建立一個a標籤來將字符串 轉換成URL

實現源碼:

function parseUrl(url) {   
     var a =  document.createElement('a');   
     a.href = url;   
     return {   
         source: url,   
         protocol: a.protocol.replace(':',''),   
         host: a.hostname,   
         port: a.port,   
         query: a.search,   
         params: (() => {   
             var ret = {}, querys = []; 
             var searchQuery = a.search.replace(/^\?/,'').split('&');
             for ( var i = 0;i < searchQuery.length; i++) {   
                 if (searchQuery[i]) { 
                     querys = searchQuery[i].split('=');   
                     ret[querys[0]] = querys[1]; 
                 }  
             }   
             return ret;   
         })(),  
         file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],   
         hash: a.hash.replace('#',''),   
         path: a.pathname.replace(/^([^\/])/,'/$1'),   
         relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],   
         segments: a.pathname.replace(/^\//,'').split('/')   
    };   
} 
parseUrl("http://www.xiyanghui.com/product/list?id=123456&sort=discount#title");

實現效果:
第二題實現效果:

三、數組元素的排列組合問題

[1, 2, 3]

指望結果:

全排列:
全排列

[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

思路:

每次取數組中的一個數,而後將剩餘的數,依次加入到該數的組合數組中
全排列思路

實現代碼:

function Permutations (target, size, origin) {
    var _arr = []
    function getArrange(target, nums, ret) {
        if (nums === 1) {
            for (var i = 0; i < target.length; i++) {
                var tmp = ret.slice();
                tmp.push(target[i]);
                _arr.push(tmp);
            }
        } else {
            nums -= 1;
            for (var i = 0; i < target.length; i++) {
                var tmp = ret.slice();
                var newTarget = target.slice();
                tmp.push(target[i]);
                newTarget.splice(i, 1);
                getArrange(newTarget, nums, tmp);
            }
        }
    }
    getArrange(target, size, origin);
    return _arr;
}
Permutations([1, 2, 3], 2, [])

實現效果:
全排列實現效果

[1, 2, 3, 4]

排列組合:
排列組合

[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

思路:

取一個數,加入到數組中,接着再取一個數加入數組,直到須要的num爲0。
排列組合思路

實現代碼:

function Permutations (arr, nums) {
  var ret = [];

  function getRet(origin, target, nums) {
    if (nums === 0) {
      ret[ret.length] = origin;
      return;
    }
    for (var i = 0; i <= target.length - nums; i++) {
      var tmp = origin.slice();
      tmp.push(target[i]);
      getRet(tmp, target.slice(i + 1), nums - 1);
    }
  }
  getRet([], arr, nums);
  return ret;
}
Permutations([1, 2, 3, 4], 3)

實現效果:
第三題實現效果

四、JS如何判斷一組數字是否連續(百詞斬筆試題)

// 當出現連續數字的時候以‘-’輸出
[1, 2, 3, 4, 6, 8, 9, 10]

指望結果:

["1-4", 6, "8-10"]

原理:

判斷先後數字是否相差爲1,若是是則加入同一個數組

實現代碼:

判斷是否連續:

var arrange = function(arr){
    var result = [],temp = [];
    arr.sort(function(source, dest){
        return source - dest;
    }).concat(Infinity).reduce(function(source, dest){
        temp.push(source);
        if(dest-source > 1){
            result.push(temp);
            temp = [];
        }
        return dest;
    });
    return result;
};

實現效果:
判斷是否連續實現效果

格式化實現:

var formatarr = function(arr) {
    var newArr = []
    var arr1 = arrange(arr)
    for (var i in arr1) {
        var str = '';
        if (arr1[i].length > 1) {
            str = arr1[i][0] + '-' + arr1[i][arr1[i].length - 1];
            newArr.push(str)
        } else {
            newArr.push(arr1[i][0]);
        }
   }
   return newArr;
}

實現效果:
第四題實現效果

五、建立子類Child,使用原型和構造函數的方式繼承父類People的方法,並調用say函數說出姓名和年齡。(詳見個人另外一篇文章前端面試問題之面向對象類)

實現代碼:

父類:

function People(name,age){
     this.name=name;
     this.age=age;
     this.say=function(){
         console.log("個人名字是:"+this.name+"我今年"+this.age+"歲!");
     };
}

原型繼承:(原型鏈相關問題請看個人另外一篇文章前端面試之原型鏈問題)

function Child(name, age){
    this.name = name;
    this.age = age;
}
Child.prototype = new People();
var child = new Child('Rainy', 20);
child.say()

實現效果:
原型繼承

構造函數繼承

function Child(name, age){
    People.call(this)
    this.name = name;
    this.age = age;
}
var child = new Child('Rainy', 20);
child.say()

實現效果:
構造函數繼承

組合繼承:

function Child(name, age){
    People.call(this);
    this.name = name;
    this.age = age;
}
Child.prototype = People.prototype;
var child = new Child('Rainy', 20);
child.say()

實現效果:
組合繼承

組合繼承優化:

function Child(name, age){
    People.call(this);
    this.name = name;
    this.age = age;
}
Child.prototype = Object.create(People.prototype);
Child.prototype.constructor = Child;
var child = new Child('Rainy', 20);
child.say()

實現效果:
組合繼承優化

未完待續

相關文章
相關標籤/搜索