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

Angular中如何将一维字符串数组每两项组合为嵌套子数组

实现方案

你可以从两种思路里选符合你需求的:

方案1:基于现有代码修改(最小改动)

你已经拿到了一维的坐标数组,只需要新增按2个元素分组的逻辑即可,同时注意new是TS/JS保留关键字,不要用作属性名避免语法错误:

hello()
{
    // 把属性名从new改成cleanedStr避免关键字冲突
    const cleanedStr = this.test.replace(/[^\d. -]/g, '');
    this.newarr = cleanedStr.split(" ");    
    const flatResult =  this.newarr.filter(e =>  e);
    // 新增分组逻辑
    const result = [];
    for(let i = 0; i < flatResult.length; i += 2) {
      result.push(flatResult.slice(i, i + 2))
    }
    // 此时result就是你要的嵌套坐标数组
    console.log(result)
}

方案2:直接匹配坐标对(容错率更高)

不用先全量清理特殊字符再拆分,直接通过正则匹配每一组坐标对,就算后续原始字符串格式有小变动(比如多余空格、括号嵌套层级变化)也不容易出错:

hello()
{
    const coordReg = /\((-?\d+\.\d+)\s+(-?\d+\.\d+)\)/g
    const result = []
    let match
    while((match = coordReg.exec(this.test)) !== null) {
      result.push([match[1], match[2]])
    }
    console.log(result)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:45:04