JavaScript: Can't access array in object -
i'm experiencing extremely strange behavior when accessing property of object.
running code:
console.log(myobj); console.log(myobj.items); console.log(myobj);
i output in console:
how possibly happen?
console.log
, during execution, outputs string representation of value in console. depending on chrome's mood, might show [object object]
or object {}
. doesn't matter.
now note little blue i
beside it. means object has been modified between time logged , time expanded in console, , shows current value (with 2 items), not value during console.log
's execution (no items). can hover on blue i
explanation.
to replicate issue, open console , run snippet:
var obj = {arr: []}; console.log(obj); console.log(obj.arr); console.log(obj); // time, see 2 object logs, 1 empty array // (representation differs time time) // > object // [] // > object obj.arr.push(1,2); // when try expand objects, array of 2 items magically appear // still see empty array ([]) in log.
this behavior differs across browsers. far remember, firebug outputs serialized version when console.log
executes, hence doesn't happen there.
debugging code
to debug kind of code, have several options:
the quickest way log stringified version of object using
json.stringify
,console.log(json.stringify(obj))
;the best way add breakpoint via sources tab. browse file in sources tab of dev tools, , add breakpoint in position. run code, , pause @ point. use scope panel inspect variables.
if can't reach code using breakpoint (probably run using
eval
or injected in console), can usedebugger;
statement. put in code @ position. run code , pause when reaches statement. use scope panel in sources tab inspect.
Comments
Post a Comment