ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

When running this JavaScript code, I got a result i didn't except .. why is that?

var x,y,funcs=[];for (x=0 ; x<5; x++) {   (function(){       funcs.push(function(){         console.log(x);       });       }())         }for (y=0; y <5 ; y++ ){   funcs[y]();}   I got5 repeated  5 times instead of the expected01234

user-image
تم إضافة السؤال من قبل Rana Alnajjar , Web developer , Lebcards
تاريخ النشر: 2015/07/02
Rahaf Nawash
من قبل Rahaf Nawash , Front End Engineer , Atypon Systems Inc.

This is a variable scope issue..

Note that the variable x in the loop is being declared in the global scope .. don’t be fooled by the block curly braces of the loop ... unlike most languages JavaScript's only block element is the function .. so the x inside the function will always see x =5

if you want your piece of code to work right  just define a new variable (z for example) at the beginning of the function  and print that in the console :

I ran the code in the question in https://jsfiddle.net/j7c6c9t4 and added the fix there.

 

Thank you

aniket kavlekar
من قبل aniket kavlekar , Software Engineer / Web Developer , Hexagon Capability Center Private Limited

variable x is defined at global scope, by the time it reaches for printing the value of x is 5 at all the instances inside the for loop. 

Jonathan de Flaugergues
من قبل Jonathan de Flaugergues , software engineer , Abbeal

You've got the 5 number 5 times because when the function is push inside funcs array, the 'x' variable is the variable of the global scope. So, when all 5 functions are called, this variable have the value x.

 

If you want to have the 0,1,2,4,5 expected as result, you have to pass the x variable into the closure on the first loop to isolate the scope.

Below, the script with the result expected :

 

var x,y,funcs=[];

 

for (x=0 ; x<5; x++) {   

  (function(x){       

    funcs.push(function(){         

      console.log(x);       

    });       

  }(x))         

}

 

for (y=0; y <5 ; y++ ){   

  funcs[y]();

المزيد من الأسئلة المماثلة