Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

javascript - Solution for Node forEach

let numbers = fs.readFileSync('numbers.txt', 'utf-8').split('
');

numbers.forEach(async numbero => {
console.alert(numbero);
})

Numbers.txt contains numbers from 100 to 999 , the problem is that numbero is giving random number between 100-999 . I want it to work like 100 101 102 103 , in order . Not random :( Please help

question from:https://stackoverflow.com/questions/65907673/solution-for-node-foreach

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use Array.sort():

numbers.sort((a, b) => a - b));

Then the array is ordered, and you can continue to the alerting. Complete code looks like this:

numbers.sort((a, b) => a - b).forEach(async numbero => {
console.alert(numbero);
})

Also - there seems to be no reason for using async, because the function you are passing to forEach is not async


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...