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

JavaScript:如何将特定格式字符串转换为二维数组?

字符串转二维数组的解决方法

你的问题出在这个字符串不符合标准JSON格式(内部字符串没有引号),直接用Array.from不行是因为它只会把字符串拆成单个字符的数组,和你要的二维数组不是一回事。下面给你两种可行的方案:

方案一:修正格式后用JSON解析

先把字符串改成合法的JSON格式,再用JSON.parse转换,这是最通用的方法:

const data = '[[Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16]]';

// 修正格式:给每个元素加上双引号,转成合法JSON
const formattedData = data
  .replace(/\[/g, '["')       // 把所有左括号替换成["
  .replace(/\s*,\s*/g, '", "')// 把逗号前后的空格替换成", "
  .replace(/\]/g, '"]');      // 把所有右括号替换成"]"

const result = JSON.parse(formattedData);
console.log(result[0][0]); // 输出 "Bday Party"
console.log(result[0][1]); // 输出 "2023-05-16"

方案二:手动分割字符串

如果不想依赖JSON解析,可以直接拆分字符串处理:

const data = '[[Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16], [Bday Party , 2023-05-16]]';

// 去掉外层的[]
const innerStr = data.slice(1, -1);
// 分割成每个子数组的字符串
const subArrStrs = innerStr.split('], [');
// 每个子字符串再分割成元素,同时去除多余空格
const result = subArrStrs.map(subStr => {
  return subStr.split(', ').map(item => item.trim());
});

console.log(result[1][1]); // 输出 "2023-05-16"

两种方法都能得到你需要的二维数组,之后就可以通过result[i][j]的方式直接访问对应元素了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:42:45