2025年最新笔试题

zijie

1.  下列输出什么结果

undefined == false; // true
undefined === false; // false
[] == []; // false
[] === []; // false
{} == {}; // Uncaught SyntaxError: Unexpected token '=='
{} === {}; // Uncaught SyntaxError: Unexpected token '==='

2.  找到字符串中,第一个不重复字符,存在的话,返回这个字符的序号;如果不存在,则返回-1;

/**
 * 如:
 * s = leetcode  return 0;
 * s = love leetcode return 2; 
 * s = aabb return -1; 
 */
const str = 'leetcode';
// (.)捕获一个字符
// (?=.*\\1)是一个正向先行断言,表示在当前位置之后存在于捕获组\\1(即前面捕获的字符)相同的字符
// g 标志标识全局匹配,这样可以匹配字符串中所有重复的字符
let reg = new RegExp('(.)(?=.*\\1)', 'g');
// 从原始字符串中去除所有匹配到的重复字符串,得到了不重复的字符
const nonRepeatedChars = str.replace(reg, '');
console.log(nonRepeatedChars);
const firstChart = nonRepeatedChars.length > 0 ? nonRepeatedChars[0] : null;

3. 根据数据动态画出dom元素

const data = {
  tagName: 'ul',
  props: {'class': 'list'},
  children: [
    {
      tagName: 'li', 
      children: ['douyin']
    },
    {
      tagName: 'li', 
      children: ['toutiao']
    }
  ]
};
<ul class="list">
  <li>douyin</li>
  <li>toutiao</li>
</ul>
const createEl = (item, parentEl) => {        
  const node = document.createElement(item.tagName);
  if (item.props) {
    const cls = Object.keys(item.props)[0];
    node.setAttribute(cls, item.props[cls]);
  }
  const childrenList = item?.children;
  const isString = Array.isArray(childrenList) && 
    childrenList.length > 0 &&
    typeof childrenList[0] === 'string';
  
  if (isString) {
    node.textContent = childrenList[0];
  }
  parentEl.appendChild(node);

  if (!isString) {
    childrenList.forEach(child => {
      createEl(child, node);
    });
  }
}
createEl(data, document.body);

4. 以下代码执行结果

第一道题

async function async1() {
  console.log("async1");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}
console.log("script start");
setTimeout(() => {
  console.log("setTimeout");
},0)
async1();
new Promise(() => {
  console.log("promise1");
}).then(() => {
  console.log("promise2");
})
console.log("script end");

输出结果:
script start
async1
async2
promise1
script end

async1 end
promise2
setTimeout

第二道题

console.log('script start');
var asyncFn = async() => {
  await new Promise((resolve) => {
    console.log("asyncFn");
    resolve();
  }).then(() => {
    console.log("asyncFn promise1");
  })
  console.log("asyncFn end");
};
asyncFn();
setTimeout(function() {
  console.log("setTimeout");
}, 0);
new Promise((resolve) => {
  console.log("Promise");
  resolve();
}).then(function(){
  console.log("promise1");
}).then(function() {
  console.log("promise2");
});
console.log("script end");

输出结果:
script start
asyncFn
Promise
script end

asyncFn promise1
promise1
asyncFn end
promise2
setTimeout

 

5. 给下列版本从小到大排序 

var versions = ["2.3", "1.45.0", "1.5", "1.2.5", "3.3.3.3.3", "6"];
注意:1.45.0小于1.5
const compareVersion = (preV,currentV) => {
  const v1Arr = preV?.toString()?.split('.');
  //注意array.splice()返回的是数组,所以先要toString
  const v2Arr = currentV?.toString()?.split('.');
  const length = Math.max(v1Arr.length, v2Arr.length);
  
  for(let i = 0; i < length;i++) {
    const v1Part = i < v1Arr.length ? v1Arr[i] : 0;
    const v2Part = i < v2Arr.length ? v2Arr[i] : 0;
    
    if (v1Part < v2Part) {
      return true;
    }else if (v1Part > v2Part) {
      return false;
    }
  }
  return false;
}
// 快速排序法 function quickSort(arr) {
if (arr.length <= 1) return arr;
// splice方法返回一个由被删除元素组成的新数组,并且原数组中的元素会被删除 let left
= [],right = [],current = arr.splice(0, 1); for(let i = 0; i < arr.length; i++) { if(compareVersion(arr[i], current)) { left.push(arr[i]); }else { right.push(arr[i]); } } return quickSort(left).concat(current, quickSort(right)); }; var versions = ["2.3", "1.45.0", "1.5", "1.2.5", "3.3.3.3.3", "6"]; console.log(quickSort(versions));

 

meituan

 1. 手动实现数组的 flat 方法(ES2019提供的方法)

Array.prototype.myFlat = function(depth = 1) {
  const result = [];
  for(const item of this) {
    if (Array.isArray(item) && depth > 0) {
      // 递归调用 myFlat 方法,深度减1
      result.push(...item.myFlat(depth -1));
    }else {
      result.push(item);
    }
  }
  return result;
}
const arr = [1,3,4,[5,6,[7,8]]];
console.log(arr.myFlat(2));

2. npm包版本比较,如果 version1 > version2 返回 1,如果 version1 < version2 返回 -1,其他情况返回0

比如:1.2.3 vs 1.2;
   1.2.3 vs 3.4.1
const compareVersion = (v1,v2) => {
  const v1Arr = v1?.toString()?.split('.');
  const v2Arr = v2?.toString()?.split('.');
  const length = Math.max(v1Arr.length, v2Arr.length); // 取最大的长度
  
  for(let i = 0; i < length;i++) {
    const v1Part = i < v1Arr.length ? v1Arr[i] : 0;
    const v2Part = i < v2Arr.length ? v2Arr[i] : 0;
    
    if (v1Part > v2Part) {
      return 1;
    }else if (v1Part < v2Part) {
      return -1;
    }
  }
  return 0
}
const result = compareVersion('1.2.3','1.2');
console.log(result);

其他常见笔试题

1. 对象数组去重

const person = [
  { id: 0, name: "小明" },
  { id: 1, name: "小张" },
  { id: 2, name: "小李" },
  { id: 3, name: "小孙" },
  { id: 1, name: "小周" },
  { id: 2, name: "小陈" },
];
//使用reduce去重
let uniqueKeys = [];
let peon = person.reduce((cur, next) => {
  if (uniqueKeys.includes(next.id)) {
    uniqueKeys.push(next.id) && cur.push(next);
  }
  return cur;
}, []) //设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);
console.log(uniqueKey);

 

2. 手写一个函数,模拟JS中的new操作符

function myNew(constructor,...args) {
  const obj = {};
  obj.__proto__ = constructor.prototype;
  const result = constructor.apply(obj, args);
  return typeof result === 'object' && result !== null ? result : obj;
}
function Person(name,age) {
  this.name = name;
  this.age = age;
}
Person.prototype.sayHello = function() {
  console.log(`hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
const person = myNew(Person, 'Alice', 30);
person.sayHello();

 

3. 实现一个函数,将驼峰命名法的字符串转换为下划线命名法

function camelToSnake(str) {
  const snakeStr = str.replace(/[A-Z]/g, (match) => {
    return '_' + match.toLowerCase();
  })
  return snakeStr.replace(/^_/, '');
}
const camelCase = 'HelloWorldJavaScript';
console.log(camelToSnake(camelCase));

 

4. 手动实现const变量的特性

const obj = {};
Object.defineProperty(obj, 'myConstant', {
  value: 42,
  writable: false,
  configurable: false,
  enumerable: true
});
console.log(obj.myConstant);
obj.myConstant = 100; // 修改该变量
console.log(obj.myConstant);// 还是输出 42,修改不成功

 5. 简单的模拟vue3中使用Proxy实现响应式的

const reactive = (obj) => {
  return new Proxy(obj, {
    // 拦截获取属性值操作
    get(target,key) {
      // 进行依赖收集等操作
      console.log(`获取属性${key}`);
      return Reflect.get(target,key);
    },
    // 拦截设置属性值操作
    set(target, key, value) {
      console.log(`设置属性${key}为${value}`);
      const result = Reflect.set(target, key, value);
      // 假设这里触发更新视图的函数
      updateView();
      return result;
    }
  })
}
function updateView() {
  console.log('更新视图');
}
const data = { name: 'John', age: 25 };
const reactiveData = reactive(data);
reactiveData.name = 'Tom';
console.log(reactiveData.age);


输出:
设置属性name为Tom
更新视图
获取属性age
25

 

posted @ 2025-03-10 12:03  转角遇到春  阅读(20)  评论(0)    收藏  举报