javascript 调试
Every so often I want to view what an object looks like at various points of an execution cycle. Many people like to use breakpoint debugging but I find it a bit annoying and tedious -- it's simply not for me. The problem comes when I log an object to the console; since other operations may have occurred between my log call and the rest of execution, I may not be seeing a true representation of the object at that moment within the console. There are a few solutions you can employ:
我经常想查看对象在执行周期的各个阶段的外观。 许多人喜欢使用断点调试,但是我发现它有点烦人和乏味-根本不适合我。 当我将对象记录到控制台时,问题就来了。 由于在我的日志调用与执行的其余部分之间可能发生了其他操作,所以那时我可能无法在控制台中看到该对象的真实表示。 您可以采用几种解决方案:
The first solution is converting the object to a JSON string to browse its contents:
第一种解决方案是将对象转换为JSON字符串以浏览其内容:
// Log the JSON representation of this object
// at *this* moment
console.log(JSON.stringify(myObject));
Now I can see every key and value of the object without needing to click around it. If you prefer to work with a real object in the debugger, simply convert the JSON object from string to an object again, effectively cloning it:
现在,我可以看到对象的每个键和值,而无需单击它。 如果您希望在调试器中使用真实的对象,只需将JSON对象从字符串再次转换为对象,即可有效地将其克隆:
// Object -> String -> Object (clone)
console.log(JSON.parse(JSON.stringify(myObject)));
Of coures this isn't a perfect solution for some people but it has worked beautifully for me in the past. Maybe I'm a lesser programmer for not liking breakpoint debugging but hey -- I tend to get things done!
当然,对于某些人来说,这不是一个完美的解决方案,但过去对我来说效果很好。 也许我是一个不太喜欢断点调试的程序员,但嘿-我倾向于把事情做好!
翻译自: https://davidwalsh.name/javascript-debugging-tip-objects
javascript 调试