当前位置:首页 > 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体验。

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处理异步输入,避免阻塞。

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

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

    js实现Scanner

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

标签: jsScanner
分享给朋友:

相关文章

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js 实现图片 放大

js 实现图片 放大

使用 CSS transform 实现图片放大 通过 CSS 的 transform: scale() 属性可以实现图片的平滑放大效果。结合 JavaScript 监听鼠标事件控制放大状态: con…

js实现左右滑动

js实现左右滑动

实现左右滑动的 JavaScript 方法 监听触摸事件 通过 touchstart、touchmove 和 touchend 事件来检测用户的手势操作。记录触摸的起始位置和移动距离,判断滑动方向。…

js 实现按钮点击

js 实现按钮点击

实现按钮点击的 JavaScript 方法 HTML 按钮元素 在 HTML 中创建一个按钮,可以通过 <button> 或 <input> 标签实现: <button…

js实现div隐藏

js实现div隐藏

使用CSS的display属性隐藏div 通过设置元素的display属性为none,可以完全隐藏div元素。这种方法不仅隐藏元素,还会从文档流中移除,不占据页面空间。 document.getEl…