You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script中Logger.log输出Set显示为空对象的原因探究

Google Apps Script 中 Set 对象用 Logger.log 输出为空的问题

问题现象

在标准 JavaScript 环境里,console.log 能正常输出 Set 对象的元素内容,但在 Google Apps Script 中,用 Logger.log 打印 Set 时,输出结果是空对象 {},示例代码如下:

function myFunction() {
  let arr = ["one", "two", "three"]
  let setTest = new Set(arr)
  Logger.log(setTest)
  // 实际输出: 
  // Info  {}
}

对比标准 JavaScript 的表现:
创建数组转 Set 的示例:

let chars = new Set(['a', 'a', 'b', 'c', 'c']);  

由于 Set 元素具有唯一性,chars 仅包含 a、b、c 三个不同元素。使用 console.log 输出:

console.log(chars);

输出结果:

Set { 'a', 'b', 'c' }

原因分析

Google Apps Script 的 Logger.log 对 Set 这类内置集合对象的格式化逻辑,和浏览器、Node.js 环境的 console.log 不同——它不会自动解析并输出 Set 内部的元素,仅打印对象的外壳结构,所以看起来是空对象,但实际上 Set 里的元素是完整存在的。

解决方法

要正确查看 Set 的内容,可通过以下几种方式:

  • 将 Set 转换为数组后打印:
    Logger.log([...setTest]);
    // 输出结果: Info  [one, two, three]
    
  • 使用 Array.from() 转换后打印:
    Logger.log(Array.from(setTest));
    // 输出结果: Info  [one, two, three]
    
  • 遍历 Set 元素逐个打印:
    setTest.forEach(item => Logger.log(item));
    // 依次输出:
    // Info  one
    // Info  two
    // Info  three
    

内容的提问来源于stack exchange,提问作者Mr. Anderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:35:23