node.js - 如何在 Node.js 中以交互方式接受数组的值
问题描述
我正在尝试从命令行以交互方式获取数组的值。以下是我为此编写的代码:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.question(`Enter Size of the array:`, (size) => {
if(parseInt(size) > 0)
{
var a = new Array(size);
var i = 0;
debugger;
// Get process.stdin as the standard input object.
var standard_input = process.stdin;
// Set input character encoding.
standard_input.setEncoding('utf-8');
// Prompt user to input data in console.
console.log("Please input Array Elements.");
// When user input data and click enter key.
standard_input.on('data', function (data) {
// User input exit.
if(i > size){
// Program exit.
console.log("User input complete");
process.exit();
}else
{
a[i] = parseInt(data);
// Print user input in console.
console.log('User Input Data : ' + data);
i++;
}
});
for(var j = 0; j < size; j++){
console.log(a[j]);
}
}
readline.close();
});
但我无法输入数组的值。在获得数组的大小后,程序只是通过显示未定义的数组值来完成,如下所示:
那么任何人都可以让我知道在 Node.js 中以交互方式接受来自命令行的输入的正确方法。
我遵循以下 SO Link 的答案: Reading value from console, interactively
我的代码现在看起来像:
var a = [4,6,1,7,9,5];
var b = new Array(5);
var k = 7, t = 0, j = 0;
var question = function(q) {
return new Promise( (res, rej) => {
readline.question( q, answer => {
res(answer);
})
});
};
(async function main() {
var answer;
while ( j < b.length ) {
answer = await question('Enter an element ');
b[j] = parseInt(answer);
j++;
}
for(var i = 0; i < b.length; i++) {
if(k === a[i]) {
t = 1;
break;
}
}
if(t === 1 ){
console.log(`Element ${k} found at position ${i}`);
process.exit();
} else {
console.log(`Element Not Found`);
}
})();
它工作正常。让我知道是否有人有更好的解决方案。提前致谢。
解决方案
推荐阅读
- github - 无法从 jupyterlab 将文件另存为 ipynb 文件
- javascript - 消息未定义
- javascript - 对 Postman 的响应,在纯 JS 中我得到:“错误:SyntaxError: Unexpected token < in JSON at position 0”
- html - HTML/CSS 列表项在左侧有太多空间
- pandas - Pandas 新列是最后 N 列的总和
- webpack - 由于意外字符,在 nextJs 中为 antd 使用 less 的 Webpack 设置失败
- jupyter-notebook - 在绘制叶图时从数组中选择颜色
- python - 查找 2 个 tensorflow 视图训练模型之间的差异(pb 文件生成中可能存在的问题)
- javascript - 在函数中返回多个值
- python - python列表理解 - 使用任何