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

while-经典面试题实战

1、while 实现数组扁平化

function flatten(arr) {
  const result = [];
  const stack = [...arr];
  
  while (stack.length) {
    const next = stack.pop();
    if (Array.isArray(next)) {
      stack.push(...next);
    } else {
      result.unshift(next);
    }
  }
  return result;
}

console.log(flatten([1, [2, [3]]])); // [1, 2, 3]

2、链表遍历(数据结构操作)

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);

let current = head;
while (current) {
  console.log(current.val); // 1 → 2 → 3
  current = current.next;
}

总结:while 循环在以下场景更具优势:

1、需要根据动态条件持续操作(如游戏循环、网络请求重试)
2、处理非线性的数据遍历(如树/图结构)
3、需要手动控制迭代进度的复杂逻辑
合理使用 while 能让代码更灵活,但要始终注意循环安全和性能影响。


http://www.kler.cn/a/575935.html

相关文章:

  • UI自动化:Python + Selenium4.6+版本 环境搭建
  • 基于置换对称性的模型融合:实现凸盆地单盆地理论
  • [Vue warn]: Failed to mount component: template or render function not defined
  • PHP:无框架、不配置服务器,仅利用URL规则设置路由
  • 《AJAX:前端异步交互的魔法指南》
  • 操作系统 2.4-内核级线程基本实现原理
  • Python通过SSH隧道访问数据库
  • 国内免费使用 Claude 3.7 Sonnt,GPT-4o,DeepSeek-R1联网极速响应
  • Ollama在AutoDL部署,CPU服务器做代理,实践中
  • ARM M3核心介绍
  • Java岗高频算法题精讲(LeetCode+场景化拆解)
  • Jetson Orin 安装 onnxruntime
  • *图论基础(5)
  • 在 CLion 中使用 Google Test 进行单元测试
  • ASP.NET 微服务网关 Ocelot+Consul+Skywalking
  • 【前端跨域】WebSocket如何实现跨域通信?原理、实践与安全指南
  • 揭开AI-OPS 的神秘面纱 第二讲-技术架构与选型分析 -- 数据采集层技术架构与组件选型分析
  • 软考架构师笔记-计算机网络
  • Uniapp项目运行到微信小程序、H5、APP等多个平台教程
  • 基于YOLO11深度学习的运动品牌LOGO检测与识别系统【python源码+Pyqt5界面+数据集+训练代码】