js实现Scanner
实现思路
在JavaScript中实现类似Java的Scanner功能,可以通过监听用户输入或解析字符串来模拟。以下是两种常见场景的实现方法。
方法一:浏览器控制台输入模拟
通过prompt或console交互实现类似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();
})();
关键点说明
-
分隔符处理
默认以空白符(空格、制表符等)作为分隔符,可通过修改delimiter正则表达式自定义。 -
异步输入
Node.js版本需使用Promise或async/await处理异步输入,避免阻塞。
-
性能优化
对于大文本处理,建议逐行读取而非一次性加载全部内容。 -
扩展功能
可添加nextInt()、nextFloat()等方法,通过类型转换实现更多功能。
以上两种方法分别适用于浏览器和Node.js环境,可根据实际需求选择实现方式。





