Home > Mobile >  How to get list instead of object in Javascript?
How to get list instead of object in Javascript?

Time:08-27

Excuse me. This is a piece of code that is related to the input in the begging part. can anyone help me find out how to get lines=[] as a list? since, after the stdin, I need to use this lines=[] as an input to the rest of the whole code.

could I get the type of list directly from this piece of code? or is there any method to change it into a list from an object?

thx a lot in advance.

code :


let lines=[];

console.log(typeof(lines));

// function readinput(liness) { // liness = liness;

    let reader = require("readline").createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    

    reader.on('line', (line) => {
        // liness.push(line);
        // push(lines,line);
        lines.push(line);
    });

    reader.on('close', () => { //受け取ったデータを用いて処理を行う
    console.log(lines);
        }
    )
// }

result: PS C:\Users\admin\Desktop\Programming\A60question MapRoute\A45bighouse> node test.js object [] object

2344 4543 245 335 56 4 56 5

[ '', '2344 4543 ', '245 335 56 ', '4 56 5', '' ]

CodePudding user response:

In JavaScript, an Array is a type of object. From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array :

In JavaScript, arrays aren't primitives but are instead Array objects

To verify that the lines object is indeed an Array, use Array.isArray(lines). It should return true for your lines variable.

CodePudding user response:

sorry, I forgot the last part of the code :

...... ....... ....... console.log(lines); console.log(typeof(lines));

Thus, it should be:


let lines=[];

console.log(typeof(lines));


// function readinput(liness) {
//         liness = liness;
        
        let reader = require("readline").createInterface({
            input: process.stdin,
            output: process.stdout,
        });
        

        reader.on('line', (line) => {
            // liness.push(line);
            // push(lines,line);
            lines.push(line);
        });

        reader.on('close', () => { //受け取ったデータを用いて処理を行う
        console.log(lines);
            }
        )
    // }

// function push(array,a){
//         array.push(a);
//     }




// lines=readinput(lines);
   console.log(lines);
   console.log(typeof(lines));
  • Related