2017-10-10 20 views
2

使用保存:Node.js的8.x的的node.js:但的readLine最後行不以陣列

目的:讀標準輸入,並將其存儲在數組

錯誤:最後一行沒有按沒有保存在陣列中。

什麼是我對javascript的誤解?異步和同步?

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很棒,但對我來說很難。

+0

一個注意:不要使用'新的數字(0)'它不會給你一個普通數字,而是一個包裹的對象,導致違反直覺的結果,如:'新號(0)==新號(0)' - >假 –

+0

感謝您的Mark_M,爲什麼你刪除你的答案....這對我很好。 – ParkDyel

回答

2

您的主要問題是,由於行數是您讀取的第一個值,您實際上不應該爲其增加計數器。一旦你實際接收到第一行數據,你應該開始遞增。

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 
 
)

由於目的通過引用平等相比(基本上檢查;如果它們指代相同的對象中記憶)。

你就可以比較它們的值:

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

但它要簡單得多,只是使用原始簡陋。

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

在你的代碼

所以:

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

謝謝!在大多數情況下,最好不要使用新的關鍵字? – ParkDyel