JavaScript function argument auto-increments -


i building nodejs web scraper has loop on data in table row. have found following 2 code snippets somehow exhibit same behavior. in first scenario how i getting incremented?

i have searched auto-incrementing variables or arguments in javascript , found nothing far.

if matters, code inside request callback, , using cheerio parse html.

snippet 1

$(this).find('td span').each(function(i) {     console.log(i); }); 

snippet 2

$(this).find('td span').each(function(i) {      console.log(i);      i++; }); 

as the documentation .each points out, argument function index. jquery calling function appropriate index every time — and jquery 1 keeping track of index.

in second example when i++ has no effect on jquery's original counter jquery keeping track of because getting passed again function when next item iterated over.

more generally, if have function being called primitive datatype argument (like number, string, etc.)

function f(x) {     // change x here } 

that won't have effect on x after particular function call has returned. so:

function f(x) {     x ++;     console.log(x); } var num = 1; f(num); // function log 2  console.log(num); // num still 1, though 

when so-called "primitives" (numbers, strings, ...) passed function, value being passed, function dealing copy.

when pass object, reference object being passed, means function dealing same original object (and can modify it).


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -