如何按要求统计订单数组总数并输出指定格式结果
问题需求
现有一组数组形式的输出内容:
[] [] [] [] [] [] [] [] [] [] [ { 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为例,处理步骤如下:
- 提取原始字符串中每个独立的数组片段
- 将每个数组片段转换为可解析的格式,计算其元素数量
- 将所有数量结果拼接为空格分隔的字符串
示例代码:
// 原始输入字符串 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
相关产品推荐
相关产品推荐

