当前位置:首页 > JavaScript

js实现Scanner

2026-02-02 07:38:25JavaScript

实现思路

在JavaScript中实现类似Java的Scanner功能,可以通过监听用户输入或解析字符串来模拟。以下是两种常见场景的实现方法。

方法一:浏览器控制台输入模拟

通过promptconsole交互实现类似Scanner的输入功能,适用于浏览器环境。

class Scanner {
  constructor(input = '') {
    this.input = input.trim();
    this.position = 0;
    this.delimiter = /\s+/; // 默认以空白符分隔
  }

  next() {
    while (this.position < this.input.length && 
           this.input[this.position].match(this.delimiter)) {
      this.position++;
    }
    let start = this.position;
    while (this.position < this.input.length && 
           !this.input[this.position].match(this.delimiter)) {
      this.position++;
    }
    return this.input.slice(start, this.position);
  }

  nextLine() {
    const lineEnd = this.input.indexOf('\n', this.position);
    if (lineEnd === -1) {
      const result = this.input.slice(this.position);
      this.position = this.input.length;
      return result;
    }
    const result = this.input.slice(this.position, lineEnd);
    this.position = lineEnd + 1;
    return result;
  }

  hasNext() {
    return this.position < this.input.length;
  }
}

// 使用示例
const scanner = new Scanner('Hello 123\nWorld');
console.log(scanner.next()); // "Hello"
console.log(scanner.next()); // "123"
console.log(scanner.nextLine()); // "World"

方法二:Node.js 终端输入

在Node.js中通过readline模块实现交互式输入,更接近Java的Scanner体验。

js实现Scanner

const readline = require('readline');

class Scanner {
  constructor() {
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.queue = [];
    this.rl.on('line', (line) => {
      if (this.queue.length > 0) {
        const resolve = this.queue.shift();
        resolve(line);
      }
    });
  }

  async next() {
    return new Promise((resolve) => {
      this.rl.question('', (input) => {
        resolve(input.trim().split(/\s+/).shift());
      });
    });
  }

  async nextLine() {
    return new Promise((resolve) => {
      this.rl.question('', resolve);
    });
  }

  close() {
    this.rl.close();
  }
}

// 使用示例(需在async函数中)
(async () => {
  const scanner = new Scanner();
  console.log('输入内容:');
  const a = await scanner.next();
  const b = await scanner.nextLine();
  console.log(`next: ${a}, nextLine: ${b}`);
  scanner.close();
})();

关键点说明

  1. 分隔符处理
    默认以空白符(空格、制表符等)作为分隔符,可通过修改delimiter正则表达式自定义。

  2. 异步输入
    Node.js版本需使用Promiseasync/await处理异步输入,避免阻塞。

    js实现Scanner

  3. 性能优化
    对于大文本处理,建议逐行读取而非一次性加载全部内容。

  4. 扩展功能
    可添加nextInt()nextFloat()等方法,通过类型转换实现更多功能。

以上两种方法分别适用于浏览器和Node.js环境,可根据实际需求选择实现方式。

标签: jsScanner
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现分页

js实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Paren…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…