简体   繁体   中英

Node.JS - For Loop combined with .split() function does not console.log() new variable

i read on different sources about the for loop and i still have kind of trouble to get it. So i thought i ask here to get it explained by somebody else.

What the Problem?

i read a txt file into an array which contents multiple login data. The format is: login:passw I want to split login:pw so i cann acces the login and password and store them in different var (let login and let passw)

What did i try?

I tried to loop through my whole array which contents currently 5 indexes and split them all in the same way so i can access login and password with different indexes.

The array is called mp

My code:

for (let i = 0; i < mp.lenght; i++) {
   let login = mp.split(":");
   console.log(login);

When i try to console log the new variable login, the programm is not loggin any yerrors, its just showing nothing. Not even undefined. if anybody has an idea why pls let me now!

Thanks

There is a small mistake in your code. You are calling the split method on the array not on array element .

Call the split method on array element .

And also there is a typo. it's length not lenght .

Try this.

 let mp = ["login1:pass1", "login2:pass2"]; for (let i = 0; i < mp.length; i++) { let login = mp[i].split(":"); console.log(login); }

You could use forEach loop for simplicity.

 let mp = ["login1:pass1", "login2:pass2"]; mp.forEach( item => { let login = item.split(":"); console.log(login); });

Because the mp variable is an array, not a record in that array. Instead of: let login = mp.split(":"); Use: let login = mp[i].split(":");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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