简体   繁体   English

node.js:readLine,但最后一行未保存在数组中

[英]node.js:readLine but last line doesn't save in array

Use: Node.js 8.x 使用:Node.js 8.x

Purpose: Reading standard input and storing it in an array 目的:读取标准输入并将其存储在数组中

Error: the Last Line doesn't save in array. 错误:最后一行未保存在数组中。

what is my misunderstanding about javascript? 我对javascript的误解是什么? async and sync? 异步和同步?

const promise = require('promise')
,   readline = require('readline');

const stdRl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

GLOBAL_COUNTER_READLINE = 0;
GLOBAL_MAPSIZE = 0;
GLOBAL_MAPDATA = [];

stdRl.on('line', (input) => {

  // first line : setMapSize
  // second line ~ GLOBAL_MAPSIZE : appendMapDataRow
  // GLOBAL_MAPSIZE + 1 line : getMapData, countChar
  if (GLOBAL_COUNTER_READLINE == 0) {

    // setMapSize;
    GLOBAL_MAPSIZE = input;

    console.log(`Map Size is : ${GLOBAL_MAPSIZE}`);

  } else if (GLOBAL_COUNTER_READLINE != GLOBAL_MAPSIZE) {

    // appendMapDataRow
    GLOBAL_MAPDATA.push(input);

  } else if(GLOBAL_COUNTER_READLINE == GLOBAL_MAPSIZE){

    //getMapData
    for (var row = 0; row < GLOBAL_MAPDATA.length; row++) {
      console.log(`${GLOBAL_MAPDATA[row]}`);
    }

    stdRl.close();
  }
  GLOBAL_COUNTER_READLINE++;
});

javascript is awesome, but it's hard to me. javascript很棒,但是对我来说很难。

Your main issue is that, since the number of lines is the first value you read, you shouldn't actually increment the counter for it. 您的主要问题是,由于行数是您读取的第一个值,因此您实际上不应为其增加计数器。 You should start incrementing once you actually receive the first line of data. 实际收到第一行数据后,您应该开始递增。

if (GLOBAL_MAPSIZE == 0) {

  GLOBAL_MAPSIZE = input;
  console.log(`Map Size is : ${GLOBAL_MAPSIZE}`);

} else if (GLOBAL_COUNTER_READLINE < GLOBAL_MAPSIZE) {

  GLOBAL_MAPDATA.push(input);
  GLOBAL_COUNTER_READLINE++; // <-- move the increment here

} else {

  for (var row = 0; row < GLOBAL_MAPDATA.length; row++) {
    console.log(`${GLOBAL_MAPDATA[row]}`);
  }

  stdRl.close();
}

Another potential future issue is that you're instantiating objects but using them as primitive values. 另一个潜在的未来问题是,您正在实例化对象,但是将它们用作原始值。

Two instances of Number are never equal: Number两个实例永远不相等:

 console.log( new Number(0) == new Number(0) // false ) 

Because objects are compared by referential equality (basically checking if they are the same instance; if they refer to the same object in memory). 因为对象是通过引用相等性进行比较的(基本上检查它们是否是相同的实例;如果它们引用内存中的同一对象)。

You could compare their values: 您可以比较它们的值:

 console.log( new Number(0).valueOf() == new Number(0).valueOf() // true ) 

But it's much simpler to just use the raw primitive. 但是,仅使用原始基元要简单得多。

 console.log( 0 == 0 // true ) 

So in your code: 因此,在您的代码中:

GLOBAL_COUNTER_READLINE = 0;
GLOBAL_MAPSIZE = 0;
GLOBAL_MAPDATA = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM