当前位置:首页 > JavaScript

js实现Scanner

2026-03-15 07:29:30JavaScript

JavaScript 实现类似 Java Scanner 的功能

JavaScript 没有内置的 Scanner 类,但可以通过以下方式模拟类似功能:

使用浏览器控制台输入

function Scanner() {
  this.nextLine = function() {
    return prompt("Enter input:");
  };
  this.nextInt = function() {
    return parseInt(prompt("Enter integer:"));
  };
  this.nextFloat = function() {
    return parseFloat(prompt("Enter float:"));
  };
}

const scanner = new Scanner();
const name = scanner.nextLine();
const age = scanner.nextInt();

使用 Node.js 的 readline 模块

const readline = require('readline');

function Scanner() {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

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

  this.nextInt = async function() {
    const input = await this.nextLine();
    return parseInt(input);
  };

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

(async function() {
  const scanner = new Scanner();
  console.log("Enter your name:");
  const name = await scanner.nextLine();
  console.log("Enter your age:");
  const age = await scanner.nextInt();
  scanner.close();
})();

处理字符串输入

如果需要从字符串中解析数据:

js实现Scanner

function Scanner(input) {
  this.input = input.trim().split(/\s+/);
  this.index = 0;

  this.hasNext = function() {
    return this.index < this.input.length;
  };

  this.next = function() {
    return this.input[this.index++];
  };

  this.nextInt = function() {
    return parseInt(this.next());
  };

  this.nextFloat = function() {
    return parseFloat(this.next());
  };
}

const scanner = new Scanner("John 25 175.5");
const name = scanner.next();
const age = scanner.nextInt();
const height = scanner.nextFloat();

注意事项

浏览器环境中的 prompt() 会阻塞 UI 线程 Node.js 版本需要使用异步/await 处理输入 字符串解析版本是同步的,适合处理预定义的输入 可以根据需要扩展更多方法如 nextDouble(), nextBoolean() 等

标签: jsScanner
分享给朋友:

相关文章

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…

js实现搜索

js实现搜索

实现搜索功能的方法 在JavaScript中实现搜索功能可以通过多种方式完成,以下是几种常见的实现方法。 使用数组的filter方法 通过数组的filter方法可以筛选出符合条件的数据项。假设有一个…