首页 > 解决方案 > 如何在 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`);
    }
})();

它工作正常。让我知道是否有人有更好的解决方案。提前致谢。

标签: node.js

解决方案


推荐阅读