文章目录
前端常考手撕题
1. 手写instanceof
function myinstanceOf_(left, right) {
let proto = left.__proto__;
let prototype = right.prototype
while (true) {
if (proto == null) return false
if (proto == prototype) return true
proto = proto.__proto__;
}
}
2. 快排
let arr = [2,13,4,3,1,3,5]
function quickSort(arr,left,right){
if(left<right){
let postions = postion(arr,left,right)
quickSort(arr,left,postions-1)
quickSort(arr,postions+1,right)
}
}
function postion(arr,left,right){
//temp基准元素
let tmp = arr[left]
while(left<right){
while(left<right&&arr[right]>=tmp){
right--
}
arr[left] = arr[right]
while(left<right&&arr[left]<=tmp){
left++
}
arr[right] = arr[left]
}
arr[left] = tmp
return left
}
quickSort(arr,0,arr.length-1)
console.log(arr)
3.数组扁平化
1. toString & split
调用数组的toString方法,将数组变为字符串然后再用split分割还原为数组
function flatten(arr) {
return arr.toString().split(',').map(function(item) {
return Number(item);
})
}
2. join & split
和上面的toString一样,join也可以将数组转换为字符串
function flatten(arr) {
return arr.join(',').split(',').map(function(item) {
return parseInt(item);
})
}
3. 递归
递归的遍历每一项,若为数组则继续遍历,否则concat
function flatten(arr) {
var res = [];
arr.map(item => {
if(Array.isArray(item)) {
res = res.concat(flatten(item));
} else {
res.push(item);
}
});
return res;
}
4.手写深拷贝
function deepCopy(obj) {
if (!obj && typeof obj !== 'object') {
throw new Error('error arguments');
}
// const targetObj = obj.constructor === Array ? [] : {};
const targetObj = Array.isArray(obj) ? [] : {
};
for (let key in obj) {
//只对对象自有属性进行拷贝
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === 'object') {
targetObj[key] = deepCopy(obj[key]);
} else {
targetObj[key] = obj[key];
}
}
}
return targetObj;
}
5. 防抖
var inputDebounce = document.getElementById('input')
// 防抖,以最后一次触发为准
function debounce(func, delay) {
let timeout;
return function(...args) {
const self = this;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(self, args);
}, delay);
}
};
const printValue = (content) => {
console.log(content);
return content.length;
};
const debouncePrint = debounce(printValue, 1000);
inputDebounce.addEventListener("keyup", (e) => debouncePrint(e.target.value));
6. 节流
<button id="btn">按钮</button>
<script type="text/javascript">
function throttle(func, delay) {
let timer = null
return function(...args) {
const self = this;
if (!timer) {
timer = setTimeout(function() {
func.apply(self, args);
timer = null;
}, delay);
}
}
}
var btn = document.getElementById('btn')
btn.onclick = throttle(function() {
console.log('haha')
}, 1000)
</script>
7. 解析URL
var url = "https: //zhidao.baidu.com/question/1768422895052400180.html?fr=iks&word=slice&ie=gbk";
function getURL(url){
let str = url.split("?")[1];
let str1 = str.split("&");
let obj = {
};
for(let i = 0; i<str1.length; i++){
let str2 = str1[i].split("=");
let key = str2[0];
let value = str2[1];
obj[key] = value;
}
return obj;
}
console.log(getURL(url))
8. promise.all()
function promiseAll(promises