Rumah > Soal Jawab > teks badan
Saya mempunyai ARR tatasusunan bersyarat dan saya mahu menulis nilai padanya dalam satu baris
Saya cuba buat ini
import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'process'; const rl = readline.createInterface({input, output}) let arr =[] console.log('Enter Values: ') for (let i = 0; i < 5; i++) { arr[i] = await rl.question('')
Tetapi apabila saya melakukan ini, saya mendapat input baris demi baris:
Enter Values: 1 A 2 B
Saya perlukan:
Enter Values: 1 A 2 B
P粉4574458582024-02-22 12:09:45
readline
用换行符分隔输入流,但您想用空格分隔它。下面的转换流可以实现这一点。请注意,它是与 for wait (...) {}
而不是 for (...) { wait }
Digunakan bersama.
var input = new stream.Transform({ readableObjectMode: true, transform(chunk, encoding, callback) { this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length) : chunk; while (true) { var offset = this.buffer.indexOf(" "); if (offset === -1) break; this.push(this.buffer.toString("utf8", 0, offset)); while (this.buffer[offset + 1] === 0x20) offset++; this.buffer = this.buffer.slice(offset + 1); } callback(); } }); console.log('Enter Values: '); process.stdin.pipe(input); let arr = []; let i = 0; for await (var number of input) { arr[i] = number; i++; if (i >= 5) break; } console.log(arr);