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
71 views
in Technique[技术] by (71.8m points)

javascript - How do you use a for loop variable as an index for a loop? (JS)

I am trying to make it so that when I run the function it checks if there is a save already. If there isn't, then it puts those values in the list. I am using nested arrays and there will be three total saves. But for some reason when I run it, it says that allSaves[L] is undefined. But when I put a zero in for the L, it works. But I can't do that. So does anyone know how I could fix that? Here is my code -


    function savingList(principal, interestRate, time, compoundNumber) {
       var allSaves = new Array();
      allSaves[0] = new Array();
      
      for(var L = 0; L < 2; L++) {
        if(allSaves[L].length == 0){
          allSaves[L] = new Array(principal, interestRate, time, compoundNumber);
        }
      }
    } 

question from:https://stackoverflow.com/questions/65623151/how-do-you-use-a-for-loop-variable-as-an-index-for-a-loop-js

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

1 Answer

0 votes
by (71.8m points)

I would suggest creating allSaves directly as an Array.map() instead of using a traditional loop block. Also note that your iterator variable L should be a let instead of a var so that it is scoped appropriately.

function savingList(principal, interestRate, time, compoundNumber) {
  return [...new Array(3)].map(saveIteration =>
    [principal, interestRate, time, compoundNumber]
  )

The phrase [...new Array(i)] is just a way of getting a map-able array of length i.


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

...