简体   繁体   中英

Items not being pushed into the array in a for loop

I have tree files en.txt, es.txt, and html.txt. I want to use the lines in the first file as patterns and the lines of the second file as replacements. The text that has to be replaced is in the third file (the HTML version of en.text).

The lines in en.txt and es.txt look like this:

Line 1
Line 2
Line 3

esStrings and esStrings are en.text and es.txt split into arrays (split on new line).

(html.txt is the same but with p tags surrounding the text)

This is the code:

fs.readFile('html.txt', 'utf8', function (err, data) {
  var result = []

  if (err) {
    return console.log(err)
  }

  for (i = 0; i < enStrings.length; i++) { 
    console.log(enStrings[i])
    var re = new RegExp(enStrings[i], "g")
    for (i = 0; i < esStrings.length; i++) { 
      result = result.push(data.replace(re, esStrings[i]))
    }
  }

  console.log(result)
})

If I do console.log(enStrings[i]) my terminal returns Line 2 indefinitely. If I do console.log(result) the script runs forever. What am I doing wrong?

Just not assign any value to result in for loop while you push data into array, replace following code of for loop with yours and try again :-

for (i = 0; i < esStrings.length; i++) { 
    result.push(data.replace(re, esStrings[i]));
}

It may help you.

You have a bug in your nested for loops using the same iterator variable i .

Also, don't assign result = result.push(... . Just perform the result.push( . It adds to the array already.

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