1、实现一个自己的instaceof(a,b)
参考资料
instaceof基础知识
instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上
obj instanceof Object;//true 实例obj在不在Object构造函数中
参考答案
实现自己的instanceof
/**
*
* @param {*} obj 实例对象
* @param {*} func 构造函数
* @returns true false
*/
const instanceOf1 = (obj, func) => {
// 必须是对象或者函数
if (!(obj && ['object', 'function'].includes(typeof obj))) {
return false
}
let proto = Object.getPrototypeOf(obj)
if (proto === func.prototype) {
return true
} else if (proto === null) {
return false
} else {
return instanceOf1(proto, func)
}
}
2、根据下面3条总结规律,写一个函数规则输入和输出。
输入:[“able”,“age”,“are”] 输出:“e”
输入:[“dog”,“racecar”,“car”] 输出:“”
輸入: [“national”, “arrival”,“mental”] 輸出: “al”
参考资料
编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。
// 确认边界条件
if(strs.length==0) {
return "";
}
// 将第一个字符串当为相同的字符前缀
let prefix = strs[0];
for(var i=1; i<strs.length; i++) {
let j =0
for(;j<strs[i].length && j<prefix.length; j++) {
if(prefix[j]!=strs[i][j]) {
break;
}
}
prefix= prefix.slice(0, j);
}
return prefix ?? ""
参考答案
var longestCommonLastfix = function(strs) {
// 确定边界
if(strs.length==0) return ""
let suffix = strs[0];
for(let i=1; i<strs.length; i++) {
let j=0
for(; j<strs[i].length && suffix.length; j++) {
if(suffix[suffix.length-j-1] != strs[i][strs[i].length-j-1] ) {
break
}
}
suffix = suffix.slice(suffix.length-j)
}
return suffix ?? ""
}
3、生成一个随机颜色。要求范围 #333333~#DDDDDD,并有50%几率生成的是#333333
function generateColors() {
const colors = [3,4,5,6,7,8,9,'a','b','c','d']
if(parseInt(Math.random()==1)) {
return "#333333"
}else {
let returnStrColors = "#"
for(let i = 0; i < 6; i++) {
returnStrColors+= colors[parseInt(Math.random()*colors.length)]
}
return returnStrColors;
}
}
4、调用下面的downloadlmg 模拟并发下载,要求:一共有 12 个图片,同一时间的并发数不超过4个,每下载完一张图片休息 100ms
urls = []
function downloadImg(url) {
return new Promise((resolve, reject) => {
const img = new Image
img.onload = function() {
console.log("loaded")
resolve()
}
img.onerror = reject
img.src = url
})
}
资料:
面试题:使用promise实现并发请求限制(最优解)
function asyncPool(poolLimit, iterable, iteratorFn) {
let i = 0;
const ret = [];
const executing = new Set();
const enqueue = function() {
if (i === iterable.length) {
return Promise.resolve();
}
const item = iterable[i++];
const p = Promise.resolve().then(() => iteratorFn(item, iterable));
ret.push(p);
executing.add(p);
const clean = () => executing.delete(p);
p.then(clean).catch(clean);
let r = Promise.resolve();
if (executing.size >= poolLimit) {
r = Promise.race(executing);
}
// 这里因为需要 每下载完一张图片休息 100ms
return r.then(()=>new Promise(r=>settimeout(r,100))).then(() => enqueue())
// return r.then(() => enqueue());
};
return enqueue().then(() => Promise.all(ret));
}
asyncPool(4,urls,downloadImg)
5、实现鼠标框选两个div
HTML
<div id="box1 "></div>
<div id="box2"></div>
CSS
#boxl { position: absolute; left: 10; top: 10px; width: 100px; height: 100px; background-color:
yellow;}
#box2 { position: absolute; left: 200px; top: 200px; width: 200px; height: 200px; background-color:
red; }
JS: