I call one function from another and the external variable disappears.

function addFakes(){ var arr=[]; for (i=1;i<=60;i++){ arr.push(i); } return arr; } function addPlayers(){ for(i=1;i<=players;i++){ player[i]={}; var deck = addFakes(); // без вызова этой функции все работает // Здесь появляется ошибка pen.js:51 Uncaught TypeError: Cannot set property 'deck' of undefined player[i].deck = deck; player[i].hand=[]; } } 

What's the matter?

    3 answers 3

    You need to write for (var i = 1; i <= 60; i ++) and for (var i = 1; i <= players; i ++) for the script to work normally. You forgot " var ". Counters are always declared INSIDE the local code of a function, so that after it is worked out, it is deleted along with the context object Local of the spent function, because nobody needs the context object Local after the spent function after it has been worked out (only the memory is clogged), the result of the function is important.

    • Thank you very much, I did not know this :) - ivan0biwan
    • you are welcome). today I told you, and tomorrow, maybe you will tell me in something that you know better. so this site works. There is still an English-speaking stackerflow. there are more people sitting there, and the likelihood of getting a good answer is even higher than in the Russian-speaking. - Dimon

    Declare the variable "i" in both functions next. in the following way:

    let i = value;

    this is a new, more correct way provided by the new ES-2015 standard for declaring local variables instead of var. More details: https://learn.javascript.ru/let-const

    At this point in the nested function, you declared the variable "i" as global. It must be declared as local.

    • No let needed here, here the author’s functions and var will work fine here! And in all browsers! - Visman
    • one
      @Visman, 1 - I just wanted to add a Dimon answer. 2 - you can use WebPack and use all the conveniences provided by the new standard and at the same time everything will work everywhere. 3 - let the author decide for himself - Evgeniy Miroshnichenko
    • thanks, but I think, I will while with var, so as not to connect too much - ivan0biwan

    I understood what was the matter. The point is in the variable i, which is in both functions

    • i is a local variable !!! - ItIsApachee
    • four
      @CraftPE, in the presented code - no, here it is global. - Visman