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

如何使用JavaScript在VS Code控制台中详细展示嵌套数组元素?

如何在VS Code控制台中详细展示嵌套数组的每个元素?

给定数组:

var myList = [["cereal", 3], ["milk", 2], ["bananas", 3], ["juice", 2], ["eggs", 6]];

尝试用console.log(myList)后,控制台仅显示:

(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]

以下几种方法可以让你在VS Code控制台看到数组的详细内容:

  • 方法1:使用console.table()
    该方法会将二维数组以表格形式展示,清晰呈现每个元素的内容:

    console.table(myList);
    

    控制台会生成包含索引、子数组元素列的表格,每行对应一组物品和数量。

  • 方法2:使用JSON.stringify()格式化输出
    将数组转换为带缩进的JSON字符串,完整展示所有层级的内容:

    console.log(JSON.stringify(myList, null, 2));
    

    输出效果:

    [
      [
        "cereal",
        3
      ],
      [
        "milk",
        2
      ],
      [
        "bananas",
        3
      ],
      [
        "juice",
        2
      ],
      [
        "eggs",
        6
      ]
    ]
    
  • 方法3:展开数组元素打印
    使用展开语法直接打印每个子数组的具体内容:

    console.log(...myList);
    

    控制台会逐个输出每个子数组:

    ["cereal", 3] ["milk", 2] ["bananas", 3] ["juice", 2] ["eggs", 6]
    
  • 方法4:遍历数组自定义输出
    通过循环遍历数组,按需求格式化输出内容:

    myList.forEach(item => {
      console.log(`物品:${item[0]},数量:${item[1]}`);
    });
    

    输出效果:

    物品:cereal,数量:3
    物品:milk,数量:2
    物品:bananas,数量:3
    物品:juice,数量:2
    物品:eggs,数量:6
    

内容的提问来源于stack exchange,提问作者Notus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:22:05