面试代码整理

 

1,获取点击元素的标签名

document.onclick = function (event) {
    var event = event || window.event;
    var tag = event.srcElement || event.target;
    console.log(tag.tagName.toLowerCase());
}

2,数组乱序

ps:19年阿里校招问数组乱序以及算法复杂度

  • 借助arr.sort
let arr = [1,2,3,4,5,6,7,8,9];
arr.sort(() => Math.random() - 0.5 );
console.log(arr);
  • 方法二
    let arr = [1,2,3,4,5,6,7,8]
    function randomSort (arr) {
        let randomArray = [];
        while (arr.length > 0) {
            let randomIndex = parseInt(Math.random()*arr.length);
            //向randomArray填入随机项
            randomArray.push(arr.[randomIndex]);
            //将填入的随机项从arr中删除
            arr.splice(randomIndex, 1);
        }
        return randomArray;
    }
    console.log(randomSort(arr));
    
  • 方法三
    let arr = [1,2,3,4,5,6,7,8,9];
    function randomRound (arr) {
        let len = arr.length;
        for(let i=0; i

3, 动态创建script标签(jsonp跨域原理)

function loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = 'text/javascript';
    if(script.readyState) {
        //IE
        script.onreadystatechange => {
            if(script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null;
                callback();
            }
        } else {
            //others
            script.onload = ()=> { callback(); }
        }
    script.src = url;
    document.body.appendChild(script);
    }
}

4,jQuery绑定事件

$('.iu').click(function(){});
$(".iu").change(function(){});
$('.iu').bind(function(){});
$('.iu').live(function(){});

5,对string对象进行扩展,使其具有删除前后空格的方法

string.prototype.trim = () => this.replace(/(^\s*)|(\s*$)/g,'')

6,获取文件扩展名

function getFileExtendName (FileName) {
    return FileName.slice(lastIndexOf('.')+1,FileName.length);
}

7,添加千分符

function commafy(num) {
    return num && num.toString().replace(/(\d)(?=(\d{3})+\.)/g,function($1, $2) {
        return $2 + ',';
    });
}

8,手写一个promise

ps:网易春招实习生前端手撕代码部分

var promise = new promise((resolve,reject) => {
    if(success) {
        resolve(value);
    } else {
        reject(error);
    }
})
promise.then((res) => {
    //success
    },(res) => {
    //failture
    })

9,class与继承

class Animal {
    constructor () {
        this.type = 'animal';
    }
    say(what) {
        console.log(this.type + 'say' + what);
    }
}
let animal = new Animal();
animal.say('hello');
class Cat extends Animal {
    constructor() {
        super()//调用父类构造函数
        this.type = 'cat';
    }
}
let ketty = new Cat();
ketty.say('hi');

10,深拷贝

ps:阿里春招19届实习生面试题

实现思路:进行多遍浅拷贝

var clone = function (v) {
    var o = v.constructor === Array ? [] : {};
    for(var i in v) {
        o[i] = typeof v[i] === 'object' ? clone(v[i]) : v[i];
    }
    return o;
}

11,node搭建服务器(最原始,可尽情忽略)

var http = require ('http');
http.createServer(function(req,res){
    //发送http头部
    res.writeHead(200,{'content-Type':'text/plain'});
    //发送响应数据
    res.end('hello');
}).listen(8888);

12,判断一个字符串中出现次数最多的字符,并统计次数

ps:某厂春招实习生面试题

//方法一
function justify(s) {
    var obj = {};
    var maxn = -1;
    var letter;
    for (var i = 0; i < s.length; i++) {
        obj[s[i]] ? obj[s[i]]++ : obj[s[i]] = 1;
        if(obj[s[i]] > maxn) {
            maxn = obj[s[i]];
            letter = s[i];
        }
    }
    console.log(letter + ':' + maxn);
}
//正则实现
function justifyStr (str) {
    var a = str.split('');
    a.sort();
    str = a.join('');
    // \1与小括号配合使用,正则表达式中的小括号"()"。是代表分组的意思。 
    //如果再其后面出现\1则是代表与第一个小括号中要匹配的内容相同。
    var pattern = /(\w)\1*/g;
    var ans = str.match(pattern);
    ans.sort(function(a, b) {
        return (b.length - a.length);
    });
    console.log(ans[0][0]+':'+ans[0].length);
}

13,原型,构造与继承(大概率面试题)

//构造函数实现继承
function Parent(age) {
    this.name = 'IU';
    this.age = '18';
}
function Child(age) {
    Parent.call(this,age);
}
var test = new Child(21);

//构造函数结合原型链实现继承
function Planet(name) {
    this.name = name;
    this.color = 'red';
}
Planet.prototype.sayName = function() {
    console.log(this.name);
}
function Moon(name,age) {
    Planet.call(this,name);
    this.age = age;
}
//实现继承
Moon.prototype = new Planet();
Moon.prototype.constructor = Moon;
Moon.prototype.sayAge = function() {
    console.log(this.age);
}

14,实现链式调用

function ClassA(){
    this.prop1 = null;
    this.prop2 = null;
    this.prop3 = null;
}
ClassA.prototype = {
    method1 : function(p1){
        this.prop1 = p1;
        return this;
    },
    method2 : function(p2){
        this.prop2 = p2;
        return this;
    },
    method3 : function(p3){
        this.prop3 = p3;
        return this;
    }
}
var obj = new ClassA();  
obj.method1(1).method2(2).method3(3);
console.log(obj);

15,数组去重

Array.prototype.uniq = function () {
    return Array.from(new Set(this));
}

16,自定义事件

ps:腾讯春招19届实习生面试题

function EventEmitter() {
    var obj = {};
    obj._callbacks = {};
    obj.on = function (name,fn) {
        this._callbacks[name] = fn;
    }
    obj.trigger = function(name,data) {
        var callback = this._callbacks[name];
        if(callback) {
            callback.call(this,data);
        }
    }
    obj.removeEvent = function(name) {
        this._callbacks[name] = null;
    }
    return obj;
}
var emitter = EventEmitter();
//添加自定义事件
emitter.on("func",function(e) {
  console.log("addEvent",e);
})
emitter.on("haha",function(e) {
  console.log("hahaahh");
})
//触发
emitter.trigger("func",{name:'IURUO'});
emitter.trigger("haha",{name:'MING'})
//移除事件
emitter.removeEvent("func");
//触发
emitter.trigger("haha",{name:'MING'});

17,事件委托/事件代理

window.onload = function() {
    var oBox = document.getElementById("box");
    oBox.onclick = function(ev) {
        var ev = ev || window.event;
		var target = ev.target || ev.srcElement;
		if(target.nodeName.toLocaleLowerCase() == 'input') {
		    switch(target.id) {
			    case 'add':
				    alert('添加');
					break;
				case 'remove':
					alert('删除');
					break;
				case 'move':
					alert('移动');
					break;
				case 'select':
					alert('选择');
					break;
			}
		}
	}
}

 

你可能感兴趣的:(面试代码整理)