当前位置:首页 > 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实现继承

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

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js图片轮播的实现

js图片轮播的实现

基础图片轮播实现 使用HTML、CSS和JavaScript实现一个简单的图片轮播效果。HTML部分定义轮播容器和图片,CSS负责样式和过渡效果,JavaScript处理逻辑。 <div cl…

js实现上传图片

js实现上传图片

使用HTML5的File API实现图片上传 HTML5的File API允许通过JavaScript访问用户选择的文件。需要创建一个文件输入元素,并监听其change事件。 <input t…

js实现文件夹

js实现文件夹

使用JavaScript创建文件夹 在浏览器端的JavaScript中无法直接操作文件系统创建文件夹,这是出于安全考虑。但在Node.js环境中可以通过文件系统模块(fs)实现。 Node.js中使…

js实现乘法

js实现乘法

实现乘法运算的方法 在JavaScript中实现乘法运算可以通过多种方式完成,以下列举几种常见方法: 基础运算符 直接使用乘法运算符*是最简单的方式: let result = 3 * 5; //…