前言
本文将不定时、长期更新,主要记录前端js的一些习题,知识点。不足处请好兄弟指正。
习题一、js实现括号匹配,包括()和[]和{}
示例:let strArr = [“(({[]}{}”,“{}()((()}}”,“{(){[]}[]}”],判断是否满足括号匹配原则。
思路
使用栈,对每一项进行判断,左括号入栈,右括号匹配则出栈。
代码
let strArr = ["(dasd({d[as]das}{}", "{}()(((fff)}}", "{(){[hhh]}[]}","{})))))"]
var isVaild = function (str) {
let symbolList = [], stack = [], flag = true // symbolList:用来存储符号的数组;stack :符号匹配使用的栈;flag:匹配标杆
str.split('').forEach(item => { //只需要括号符号,去掉其他元素
if (['(', ')', '{', '}', '[', ']'].includes(item)) {
symbolList.push(item)
}
})
symbolList.forEach(item => { //左括号入栈,右括号进行匹配。匹配成功则进行下一项,失败则标杆为false
if (['(', '{', '['].includes(item)) {
stack.push(item)
return;
}
if (['()', '{}', '[]'].includes(stack.at(-1) + item)) {
stack.pop()
} else {
flag = false
}
})
return stack.length === 0 && flag //判断是否有剩余和标杆值
}
strArr.forEach(item => {
console.log(isVaild(item));
})
习题二、手写 call,apply和bind
- call
Function.prototype.myCall = function (context) {
if(typeof this !== 'function'){
throw new Error('not function')
}
context = context||window
context.fn = this
return arguments[1]?context.fn(...[...arguments].slice(1)):context.fn()
}
- apply
Function.prototype.myApply = function (context) {
if(typeof this !== 'function'){
throw new Error('not function')
}
context = context||window
context.fn = this
return arguments[1]?context.fn(...arguments[1]):context.fn()
}
- bind
Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
throw new Error('不是一个函数');
}
context = context || window;
let params = arguments[1] ? [].slice.call(arguments, 1) : [];
return () => {
this.apply(context, params);
}
}
习题三、闭包实现防抖,节流
- 防抖
短时间高频率触发只有最后一次触发成功
举例:搜索框,连续输入会多次发请求。
function debounce(fn, delay = 3000) {
let timer = null
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
}
}
- 节流
短时间高频率触发只有第一次触发成功
function throttle(fn, wait) {
let timer = null
return function () {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
clearTimeout(timer)
timer = null
}, wait);
};
}
习题四、new和object.create区别,手写new
- new
function my_new(fun, ...args) {
let obj = Object.create(fun.prototype)
let res = fun.apply(obj, args)
console.log(res instanceof Object );
return res instanceof Object ? res : obj
}
- object.create
Object.create = function (prototype) {
function fun() {}
fun.prototype = prototype
return new fun()
}
- 区别
new创建的实例身上有构造函数实现的自身属性,object.create创建的新对象身上只能访问prototype原型对象的上属性。
通常使用object.create(null)来创建一个空对象,该对象的__proto__为null。