当前位置: 首页 > news >正文

30道JS高频经典笔试题集合+详解(一)

JavaScript 高频笔试题集合(一)

目录

  1. 基础语法类
  2. 闭包与作用域
  3. 原型链与继承
  4. 异步编程
  5. ES6+新特性
  6. 数组与对象操作
  7. 函数式编程
  8. 性能优化

基础语法类

1. 数据类型判断

题目: 请写出判断数据类型的几种方法,并说明它们的区别。

答案:

// 方法1: typeof
console.log(typeof 123); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (这是一个历史遗留bug)
console.log(typeof []); // "object"
console.log(typeof {}); // "object"// 方法2: instanceof
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true// 方法3: Object.prototype.toString.call()
function getType(obj) {return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
console.log(getType([])); // "array"
console.log(getType({})); // "object"
console.log(getType(null)); // "null"

详解:

  • typeof:适用于基本数据类型,但对于null和数组会返回"object"
  • instanceof:检查对象的原型链,适用于引用类型
  • Object.prototype.toString.call():最准确的类型判断方法

2. 变量提升

题目: 解释以下代码的输出结果

console.log(a); // ?
var a = 1;
function test() {console.log(a); // ?var a = 2;console.log(a); // ?
}
test();
console.log(a); // ?

答案:

undefined
undefined
2
1

详解:
由于变量提升,代码实际执行顺序为:

var a; // 提升到顶部,值为undefined
console.log(a); // undefined
a = 1;function test() {var a; // 函数内部的a提升到函数顶部console.log(a); // undefined (局部变量a遮蔽了全局变量)a = 2;console.log(a); // 2
}
test();
console.log(a); // 1 (全局变量a)

3. this指向问题

题目: 分析以下代码中this的指向

var obj = {name: 'obj',getName: function() {return this.name;}
};var getName = obj.getName;
console.log(obj.getName()); // ?
console.log(getName()); // ?
console.log(getName.call(obj)); // ?

答案:

"obj"
undefined (严格模式下会报错)
"obj"

详解:

  • obj.getName():this指向obj对象
  • getName():this指向全局对象(浏览器中是window),window.name为undefined
  • getName.call(obj):通过call显式绑定this为obj

闭包与作用域

4. 经典闭包问题

题目: 以下代码输出什么?如何修改让它输出0,1,2,3,4?

for (var i = 0; i < 5; i++) {setTimeout(function() {console.log(i);}, 100);
}

答案: 输出5个5

解决方案:

// 方案1: 使用立即执行函数
for (var i = 0; i < 5; i++) {(function(j) {setTimeout(function() {console.log(j);}, 100);})(i);
}// 方案2: 使用let
for (let i = 0; i < 5; i++) {setTimeout(function() {console.log(i);}, 100);
}// 方案3: 使用bind
for (var i = 0; i < 5; i++) {setTimeout(function(j) {console.log(j);}.bind(null, i), 100);
}

5. 闭包的实际应用

题目: 实现一个计数器函数,每次调用返回递增的数字

答案:

function createCounter() {let count = 0;return function() {return ++count;};
}const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3// 高级版本:支持初始值和步长
function createAdvancedCounter(initial = 0, step = 1) {let count = initial;return {next: () => (count += step),reset: () => (count = initial),current: () => count};
}

原型链与继承

6. 原型链理解

题目: 解释原型链的工作原理,并实现一个简单的继承

答案:

// 原型链示例
function Person(name) {this.name = name;
}Person.prototype.sayHello = function() {console.log(`Hello, I'm ${this.name}`);
};function Student(name, grade) {Person.call(this, name); // 继承属性this.grade = grade;
}// 继承方法
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;Student.prototype.study = function() {console.log(`${this.name} is studying in grade ${this.grade}`);
};const student = new Student("Alice", 10);
student.sayHello(); // "Hello, I'm Alice"
student.study(); // "Alice is studying in grade 10"

7. 手写instanceof

题目: 实现instanceof操作符

答案:

function myInstanceof(left, right) {if (typeof left !== 'object' || left === null) {return false;}let prototype = right.prototype;let proto = Object.getPrototypeOf(left);while (proto !== null) {if (proto === prototype) {return true;}proto = Object.getPrototypeOf(proto);}return false;
}// 测试
console.log(myInstanceof([], Array)); // true
console.log(myInstanceof({}, Object)); // true
console.log(myInstanceof("hello", String)); // false

异步编程

8. Promise实现

题目: 手写一个简单的Promise

答案:

class MyPromise {constructor(executor) {this.state = 'pending';this.value = undefined;this.reason = undefined;this.onFulfilledCallbacks = [];this.onRejectedCallbacks = [];const resolve = (value) => {if (this.state === 'pending') {this.state = 'fulfilled';this.value = value;this.onFulfilledCallbacks.forEach(fn => fn());}};const reject = (reason) => {if (this.state === 'pending') {this.state = 'rejected';this.reason = reason;this.onRejectedCallbacks.forEach(fn => fn());}};try {executor(resolve, reject);} catch (error) {reject(error);}}then(onFulfilled, onRejected) {return new MyPromise((resolve, reject) => {if (this.state === 'fulfilled') {setTimeout(() => {try {const result = onFulfilled(this.value);resolve(result);} catch (error) {reject(error);}});}if (this.state === 'rejected') {setTimeout(() => {try {const result = onRejected(this.reason);resolve(result);} catch (error) {reject(error);}});}if (this.state === 'pending') {this.onFulfilledCallbacks.push(() => {setTimeout(() => {try {const result = onFulfilled(this.value);resolve(result);} catch (error) {reject(error);}});});this.onRejectedCallbacks.push(() => {setTimeout(() => {try {const result = onRejected(this.reason);resolve(result);} catch (error) {reject(error);}});});}});}
}

9. async/await错误处理

题目: 如何优雅地处理async/await中的错误?

答案:

// 方法1: try-catch
async function fetchData() {try {const response = await fetch('/api/data');const data = await response.json();return data;} catch (error) {console.error('Error fetching data:', error);throw error;}
}// 方法2: 封装错误处理函数
function to(promise) {return promise.then(data => [null, data]).catch(err => [err, null]);
}async function fetchDataSafely() {const [error, data] = await to(fetch('/api/data'));if (error) {console.error('Fetch failed:', error);return null;}return data;
}// 方法3: 统一错误处理装饰器
function asyncErrorHandler(fn) {return async function(...args) {try {return await fn.apply(this, args);} catch (error) {console.error('Async function error:', error);// 可以在这里进行统一的错误上报throw error;}};
}

10. 并发控制

题目: 实现一个并发请求控制函数,限制同时进行的请求数量

答案:

class RequestPool {constructor(maxConcurrent = 3) {this.maxConcurrent = maxConcurrent;this.currentCount = 0;this.queue = [];}async add(requestFn) {return new Promise((resolve, reject) => {this.queue.push({requestFn,resolve,reject});this.process();});}async process() {if (this.currentCount >= this.maxConcurrent || this.queue.length === 0) {return;}this.currentCount++;const { requestFn, resolve, reject } = this.queue.shift();try {const result = await requestFn();resolve(result);} catch (error) {reject(error);} finally {this.currentCount--;this.process();}}
}// 使用示例
const pool = new RequestPool(3);const requests = Array.from({ length: 10 }, (_, i) => () => fetch(`/api/data/${i}`).then(res => res.json())
);Promise.all(requests.map(req => pool.add(req))).then(results => console.log('All requests completed:', results)).catch(error => console.error('Some requests failed:', error));

ES6+新特性

11. 解构赋值高级用法

题目: 展示解构赋值的各种用法

答案:

// 数组解构
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest); // 1 2 [3, 4, 5]// 对象解构
const { name, age, ...others } = { name: 'John', age: 30, city: 'NYC', job: 'Developer' };
console.log(name, age, others); // "John" 30 {city: "NYC", job: "Developer"}// 重命名
const { name: userName, age: userAge } = { name: 'Alice', age: 25 };
console.log(userName, userAge); // "Alice" 25// 默认值
const { x = 10, y = 20 } = { x: 5 };
console.log(x, y); // 5 20// 嵌套解构
const user = {id: 1,profile: {name: 'Bob',address: {city: 'Shanghai',country: 'China'}}
};const {profile: {name,address: { city }}
} = user;
console.log
http://www.lryc.cn/news/605404.html

相关文章:

  • LTE广播信道
  • 基于Java对于PostgreSQL多层嵌套JSON 字段判重
  • 视觉语言模型在视觉任务上的研究综述
  • 微服务的编程测评系统8-题库管理-竞赛管理
  • 闸机控制系统从设计到实现全解析 第 2 篇:数据库设计与 SqlSugar 集成方案
  • Mysql事务原理
  • HPC超算、集群计算
  • 下拉加载问题
  • HTML应用指南:利用POST请求获取全国公牛门店位置信息
  • Elasticsearch(ES)基础语法(笔记)(持续更新)
  • VSCode高效集成开发全流程优化
  • colima 修改镜像源为国内源
  • docker:将cas、tomcat、字体统一打包成docker容器
  • QT---》文件MD5码的获取与验证
  • 结合C++红黑树与AI人工智能的应用
  • Linux启动防火墙提示提示 Active: failed (Result: timeout)
  • 7.pcl滤波(一)
  • IFCVF驱动+vhost-vfio提高虚拟机网络性能
  • 在线免疫浸润分析
  • Kimi-K2技术报告解读:万亿参数大模型,开源模型新SOTA
  • 如何判断一个数据库是不是出问题了?
  • STM32F1 Flash的操作
  • Python Day19 时间模块 和 json模块 及例题分析
  • C语言15-构造数据类型、位运算符、内存管理
  • 2018 年 NOI 最后一题题解
  • yolo8+阿里千问图片理解(华为简易版小艺看世界)
  • CSS 工作原理
  • 卡尔曼滤波通俗入门:预测、测量与最优融合
  • 重生之我在暑假学习微服务第五天《Docker部署项目篇》
  • 【人工智能99问】混合专家模型(MoE)是如何训练的?(18/99)