前端----JS 面试题 部分阿里、百度一面
- [1, 2, 3, 4, 5, 6, 7, 8, 9] => [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
- EventLoop的执行机制
- 手写发布订阅模式
- 实现一个链式调用的query方法
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
// 适合用于各种分片
var paramsArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var resultArr = [];
// 分片常用的四个参数
/**
前三个不用说,目的很明确,就是分片。
最后一个用于跳出循环
*/
var arrSize = paramsArr.size; // 数组大小
var chunk_size = 3; // 分片大小
var chunks = Math.ceil(arrSize / chunk_size); // 获取切片的个数
var currentChunk = 0; // 当前分片下标
function sliceArr(arr, chunks) {
var result = [];
for (var i = 0; i < chunks; i++) {
const start = currentChunk * chunk_size;
const end = start + chunk_size >= arrSize ? arrSize : start + CHUNK_SIZE;
if(currentChunk > result ){
break;
}else{
result.push(arr.slice(start,end ));
}
currentChunk++;
}
return result;
}
var resultArr = sliceArr(paramsArr, chunks);
console.log(resultArr);
EventLoop的执行机制
console.log('1');
function promiseFn() {
return new Promise((resolve, reject) => {
setTimeout(()=> {
console.log('2');
})
resolve('3');
console.log('4')
})
}
promiseFn().then(res => {
console.log(res);
});
手写发布订阅模式
class EventBus {
constructor() {
this.events = {}; // 存储事件及其对应的回调函数列表
}
// 订阅事件
subscribe(eventName, callback) {
this.events[eventName] = this.events[eventName] || []; // 如果事件不存在,创建一个空的回调函数列表
this.events[eventName].push(callback); // 将回调函数添加到事件的回调函数列表中
}
// 发布事件
publish(eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(callback => {
callback(data); // 执行回调函数,并传递数据作为参数
});
}
}
// 取消订阅事件
unsubscribe(eventName, callback) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter(cb => cb !== callback); // 过滤掉要取消的回调函数
}
}
}
// 创建全局事件总线对象
const eventBus = new EventBus();
const callback1 = data => {
console.log('Callback 1:', data);
};
const callback2 = data => {
console.log('Callback 2:', data);
};
// 订阅事件
eventBus.subscribe('event1', callback1);
eventBus.subscribe('event1', callback2);
// 发布事件
eventBus.publish('event1', 'Hello, world!');
// 输出:
// Callback 1: Hello, world!
// Callback 2: Hello, world!
// 取消订阅事件
eventBus.unsubscribe('event1', callback1);
// 发布事件
eventBus.publish('event1', 'Goodbye!');
// 输出:
// Callback 2: Goodbye!
实现一个链式调用的query方法
/**
要求实现一个 query 方法,返回一个新的数组,query 方法内部有 过滤、排序 等操作,并且支持链式调用,调用最终的 execute 方法返回结果
*/
const data = [
{ id: 1, name: 'Alice', age: 20, gender: 'female' },
{ id: 2, name: 'Bob', age: 25, gender: 'male' },
{ id: 3, name: 'Charlie', age: 30, gender: 'male' },
{ id: 4, name: 'David', age: 35, gender: 'male' },
{ id: 5, name: 'Ella', age: 40, gender: 'female' }
];
class Query {
constructor(data) {
this.results = data;
}
// 返回this用于链式调用
filter(callback) {
this.results = this.results.filter(callback);
return this;
}
// 参数是箭头函数
sort(callback) {
this.results = this.results.sort(callback);
return this;
}
// 返回results
execute() {
return this.results;
}
}
const result = new Query(data)
.filter((item) => item.age > 25)
.sort((a, b) => a.age - b.age)
.execute();
console.log(result);