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

如何按要求统计订单数组总数并输出指定格式结果

问题需求

现有一组数组形式的输出内容:

[] [] [] [] [] [] [] [] [] [] [ { order_status: 'Received' } ] [{ order_status: '1' },{ order_status: '1'},{ order_status: 'Accepted'}] [] [] [] [] [] [] [] [] [ { order_status: 'Received' } ] [] [ { order_status: 'Accepted' } ] []

需要统计每个数组的订单总数:空数组显示0,非空数组显示内部对象的数量,最终输出格式要求如下:

0 0 0 0 0 0 0 0 0 0 1 3 0 0 0 0 0 0 0 0 1 0 1 0
解决方案

以JavaScript为例,处理步骤如下:

  1. 提取原始字符串中每个独立的数组片段
  2. 将每个数组片段转换为可解析的格式,计算其元素数量
  3. 将所有数量结果拼接为空格分隔的字符串

示例代码:

// 原始输入字符串
const inputStr = "[] [] [] [] [] [] [] [] [] [] [ { order_status: 'Received' } ] [{ order_status: '1' },{ order_status: '1'},{ order_status: 'Accepted'}] [] [] [] [] [] [] [] [] [ { order_status: 'Received' } ] [] [ { order_status: 'Accepted' } ] []";

// 匹配所有[]包裹的数组片段
const arraySegments = inputStr.match(/\[.*?\]/g);

// 转换并计算每个数组的长度
const output = arraySegments.map(segment => {
  // 替换单引号为双引号,确保JSON解析正常
  const validJson = segment.replace(/'/g, '"');
  const arr = JSON.parse(validJson);
  return arr.length;
}).join(' ');

console.log(output);
// 输出结果:0 0 0 0 0 0 0 0 0 0 1 3 0 0 0 0 0 0 0 0 1 0 1 0

内容的提问来源于stack exchange,提问作者Prajwal K Rao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:40:47