【问题标题】:How can I see the contents of a JavaScript Map using the node debugger?如何使用节点调试器查看 JavaScript Map 的内容?
【发布时间】:2017-05-29 18:42:08
【问题描述】:

我在 NodeJS 中使用控制台调试器并想查看 Map 对象。这是我想练习的简单测试脚本。

'use strict'

const data = new Map()

const readline = require('readline-sync')
let input
do {
  input = String(readline.question('enter command: ')).trim()
  debugger
  if (input.indexOf('add ') === 0) {
    const space = input.indexOf(' ')
    const item = input.substring(space).trim()
    console.log(`adding '${item}'`)
    let qty = 1
    debugger
    if (data.has(item)) qty = data.get(item) + 1
    data.set(item, qty)
  }
  if (input.indexOf('list') === 0) {
    data.forEach( (val, key) => {
        process.stdout.write(`${key}\t${val}\n`)
    })
  }
} while (input !== 'exit')

所以我在调试模式下启动脚本并将观察者附加到data 对象。

node debug simpleDebug.js
< Debugger listening on 127.0.0.1:5858
connecting to 127.0.0.1:5858 ... ok
break in simpleDebug.js:2
  1 
> 2 'use strict'
  3 
  4 const data = new Map()
debug> watch('data')
debug> c
debug> enter command: add cheese
break in simpleDebug.js:10
Watchers:
  0: data = {"handle":15,"type":"map","text":"#<Map>"}

  8 do {
  9     input = String(readline.question('enter command: ')).trim()
>10     debugger
 11     if (input.indexOf('add ') === 0) {
 12         const space = input.indexOf(' ')
debug>

如您所见,调试器不显示映射中存储的值。我假设这些是 "text" 键的一部分,但我怎样才能添加一个观察者呢?

【问题讨论】:

    标签: javascript node.js dictionary node-debugger


    【解决方案1】:

    您可以使用spread operator 将地图转换为二维键值数组

    watch('[...data]')

    或者如果您想查看特定键的值

    watch("data.get('myKey')")

    或者只是键

    watch('[...data.keys()]')

    或者只是值

    watch('[...data.values()]')

    或者,您可以考虑使用常规对象并观察该变量。比如:

    var obj = {};
    //your code
    if(obj[item]){
        obj[item] += 1;
    } else {
        obj[item] = 1;
    }
    

    watch('obj')

    【讨论】:

    • 真是这样的救命稻草。谢谢你!
    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 2010-09-11
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多