Apparently conflicting Javascript function behavior

The next feature suggested by "Doug Crockford: JavaScript: Good Details." works great.

var fibonacci = function () { var memo = [0, 1]; var fib = function (c) { console.debug(memo, c, memo[c]); result = memo[c]; if (typeof result !== 'number'){ result = fib(c - 1) + fib(c - 2); memo[c] = result; } return result; }; return fib; }(); console.log(fibonacci(3)); 

But let's take a closer look at what happens with line 4

 console.debug(memo, c, memo[c]); 

He shows the following result, which is the opposite of what was expected.

 memo, c, memo[c] [0, 1, 1, 2] 3 undefined //contradictory behavior because I expect to have memo = [0, 1] [0, 1, 1, 2] 2 undefined //contradictory behavior [0, 1, 1, 2] 1 1 [0, 1, 1, 2] 0 0 [0, 1, 1, 2] 1 1 2 

Some ideas?

+1
source share
1 answer

This is a problem with the exit of the Chrome console. Chrome seems to dynamically update the output in order to somehow reflect the contents of the array. If you run it in Firebug, the output will look like this:

 [0, 1] 3 undefined [0, 1] 2 undefined [0, 1] 1 1 [0, 1] 0 0 [0, 1, 1] 1 1 2 

It also makes sense when you try to go through the code in your head: console.debug is the first statement in fib . The first time fib is called, memo is [0, 1] , since there were no changes to the array. c 3 , so you get undefined . Thus, on the first call, memo cannot be [0, 1, 1, 2] no matter what the console shows.

Some JavaScript consoles seem to exhibit this behavior (one way or another) when you register references to arrays or objects. In these cases, it is often better to set breakpoints and go step by step.

Update: Firebug seems to have fixed this problem (if it ever existed), but it still exists in the light of Firebug.

+4
source

Source: https://habr.com/ru/post/1412181/


All Articles