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

使用:Node.js 8.x

目的:读取标准input并将其存储在一个数组中

错误:最后一行不保存在数组中。

什么是我对JavaScript的误解? asynchronous和同步?

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太棒了,但对我来说很难。

你的主要问题是,由于行数是你读的第一个值,所以你不应该为它增加计数器。 一旦你实际接收到第一行数据,你应该开始递增。

 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(); } 

另一个潜在的未来问题是,你正在实例化对象,但使用它们作为原始值。

Number两个实例永远不会相等:

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