面试题中遇到的算法与js技巧

时间:2023-03-08 17:36:20
面试题中遇到的算法与js技巧

近一周在忙着面试,本月第一次更博,甚是想念。

基本上大公司都会要求一些算法或者数据结构类的东西,挑了些有意思的敲了下。这方面自己还不是很精通,只能一步一个脚印来积累了。

1.根据查询字符串获取对象数据,可自行根据需求选择格式,此处以key:value的格式生成

// 这里可以使用正则匹配,但仔细向后,字符串的一些基本方法完全可以解决问题
var str = 'www.test.com/test?str1=aa&str2=bb&str3=cc';
function queryStr (str) {
var target = str.substr(str.indexOf('?') + 1);
var groupItem = target.split('&');
var temp = {}
for(var i=0; i<groupItem.length; i++) {
var key = groupItem[i].split('=')[0];
var value = groupItem[i].split('=')[1];
temp[key] = value;
}
return temp;
}
console.log(queryStr(str))

2.数组随机置换,时间复杂度很重要!!

// 普通的随机置换都可以,但实际中更看重的时时间复杂度低的算法
var array = [1,5,9,6,2,6];
function tempArray (array) {
var len = array.length;
var temp = [];
while(len--) {
var ran = Math.floor( Math.random() * len);
temp.push((array.splice(ran,1))[0])
}
return temp
}
console.log(tempArray(array))

3.模拟new过程

大致分为五部:

(1) 创建一个空对象

(2)对象的__proto__属性指向构造函数的prototype对象

(3)对象的constructor属相改为构造函数

(4)更正this指针的指向

(5)返回对象

     // 构造函数
function People (name, sex) {
this.name = name;
this.sex = sex;
this.eat = function () {
console.log(this.name + ' eat')
}
} function newPeople (name, sex) {
// 创建空对象
var obj = {}
// 指定__proto__ 属性
obj.__proto__ = People.prototype;
// 指定构造函数
obj.constructor = People;
// this指针更正
People.call(obj, name, sex);
// 返回对象
return obj;
} var p1 = new People('kevin','male')
var p2 = newPeople('jenny','female')
console.log(p1)
p1.eat()
console.log(p2)
p2.eat()

4.原生js实现自定义事件,面向对象思维实现

    // 自定义事件类
function MyEvent () {
this.evList = {}
this.addEvent = function (type, fn) {
if(typeof fn !== 'function') return
this.evList[type] = fn
}
this.dispatchEvent = function (type, data) {
var dataObj = {}
dataObj.data = data
this.evList[type](dataObj)
}
} var ev = new MyEvent()
// 添加自定义事件
ev.addEvent('test', function (e) {
alert(e.data)
})
// 触发自定义事件
document.querySelector('.btn').onclick = function () { ev.dispatchEvent('test', 'pomelo')
}

5. 数组去重的四种方法,同样,时间复杂度很重要!!

var arr = [1,1,2,3,5,5]
// 从前向后逐个比较,相同的删除
Array.prototype.distinct1 = function () {
var arr = this;
for(var i=0; i<arr.length; i++) {
for(var j=i+1; j<arr.length; j++) {
if(arr[i] === arr[j]) {
arr.splice(j,1)
j = ++i;
}
}
}
return arr
}
// 从前向后比较,不相同的push到新数组
Array.prototype.distinct2 = function () {
var arr = this;
var temp = [];
for(var i=0; i<arr.length; i++) {
for(var j=i+1; j<arr.length; j++) {
if(arr[i] === arr[j]) {
j = ++i;
}
}
temp.push(arr[i])
}
return temp
} // 利用对象属性名不能重复的特性
Array.prototype.distinct3 = function () {
var obj = {};
var arr =this;
var temp = [];
for(var i=0; i<arr.length; i++) {
if(!obj[arr[i]]) {
temp.push(arr[i])
obj[arr[i]] = 1;
}
}
return temp
} // 利用indexOf 如果无法匹配到相同的,push进新数组
Array.prototype.distinct4 = function () {
var arr = this;
var temp = [];
arr.forEach(function (item, i) {
var num = arr.indexOf(item, i+1)
if(num === -1) {
temp.push(item)
}
})
return temp
} console.log(arr.distinct1())
console.log(arr.distinct2())
console.log(arr.distinct3())
console.log(arr.distinct4())