【问题标题】:Is there a way to get console.table to execute property accessor functions?有没有办法让 console.table 执行属性访问器函数?
【发布时间】:2016-11-03 17:13:06
【问题描述】:

我有一个包含许多 getter 属性的对象集合。我希望能够使用console.table 在控制台中打印这些值的子集。当前的实现似乎不允许这样做,有解决方法吗?

let obj = {
    get prop() {
        return "getter";
    }
    id:1
}

console.table([obj]); // prints only index, and id
console.table([obj], ["prop"]); // prints only index, but still not "prop"

【问题讨论】:

    标签: javascript google-chrome console


    【解决方案1】:

    console.table api 是still non-standard

    目前 - chrome 无法使用 getters values,如果您检查 firefox - 所有由 getter 定义的值都将打印为 undefined

    请注意,这与hasOwnProperty'prop' in obj 无关(两者都很好用),但它可能与Object.getOwnPropertyDescriptor 有关。

    在您的示例中(适用于 Chrome 和 Firefox):

    Object.getOwnPropertyDescriptor(obj, 'id').value
    // 1
    Object.getOwnPropertyDescriptor(obj, 'prop').value
    // undefined
    

    但是,如果是这种情况,我希望 Chrome 也会显示 prop 列(即使其中包含未定义的值)。

    您可以使用这个 sn-p 在您的浏览器上进行测试:

    let obj = {
        get prop() {
            return "getter";
        },
        id:1
    }
    
    console.log('Log "t in obj"')
    for (var t in obj) {
      console.log(t, obj[t]);
    }
    console.log('')
    
    console.table([obj]);
    console.table([obj], ["id"]);
    console.table([obj], ["prop"]); // currently returns a column of 'undefined' in firefox, and in chrome that column doesn't exists.

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 2015-10-22
      • 2014-06-20
      • 2022-08-23
      • 2022-08-02
      • 1970-01-01
      • 2010-09-07
      • 2021-10-30
      • 2011-04-15
      相关资源
      最近更新 更多