Apparently contradictory behavior of Javascript function

后端 未结 1 515
抹茶落季
抹茶落季 2021-01-23 11:53

The following function proposed by \"Doug Crockford: JavaScript: The Good Parts.\" works great.

var fibonacci = function () {
  var memo = [0, 1];
  var fib = fu         


        
1条回答
  •  再見小時候
    2021-01-23 12:30

    It's a problem with Chrome's console output. Chrome seems to dynamically update the output to reflect the content of the array somehow. If you run it in Firebug, the output is:

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

    Also it 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] as there haven't been made any changes to the array. c is 3, so you get undefined. So in the first invocation, memo cannot be [0, 1, 1, 2] no matter what the console shows.

    Some JavaScript consoles seem to show such a behaviour (in one way or an other), when you log references to arrays or objects. In these cases it is often better to set breakpoints and go through the code step by step.

    Update: It seems Firebug fixed this issue (if it ever existed), but it still seems to exist in Firebug light.

    0 讨论(0)
提交回复
热议问题