【问题标题】:Place every 2 strings into an array in an array in angular将每 2 个字符串放入 angular 数组中的数组中
【发布时间】:2021-12-19 14:29:13
【问题描述】:

我正在处理一个有角度的项目。 我有一个如下所示的字符串,我使用正则表达式整理了所有特殊字符。 现在,我希望前 2 个字符串位于方括号中,后两个字符串位于另一个方括号中,如坐标,输出应如下所示。 请帮我实现功能。

test: any = "((-1.23568 75.87956), (-1.75682 22.87694))"

我的 ts 代码如下:


  hello()
  {
      this.new = ( this.test.replace(/[^\d. -]/g, ''));
      this.newarr = this.new.split(" ");    
      const result =  this.newarr.filter(e =>  e);
  }

我在结果数组中的最终输出如下:

["-1.23568", "75.87956", "-1.75682", "22.87694"]

期望的输出

[ ["-1.23568", "75.87956"], ["-1.75682", "22.87694"] ]

【问题讨论】:

    标签: javascript arrays string typescript


    【解决方案1】:

    另一种方法是使用String.match() 获取每组坐标,然后将Array.map()String.split() 分成对。

    let test = "((-1.23568 75.87956), (-1.75682 22.87694))";
    const result = test.match(/[\d.-]+\s[\d.-]+/g).map(s => s.split(/\s/));
    console.log('Result:', result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 感谢您的回复。截至目前,我们将每 2 个字符串放入一个数组中。但是,如果我们想将每 2 个字符串放在方括号之间并将其传递给变量,解决方案是什么?例如:test = [[string1, string2],[string1, string2], 以此类推]。如果我想读取索引 0 - 值应该是 test = [string1, string2] 等等我可以读取任何索引并且它应该带有方括号。
    • 我希望在这种情况下可以修改解决方案,如果您将该变体添加到问题中会有所帮助,谢谢!
    【解决方案2】:

    例如,您可以使用Array.prototype.splice()。 这个函数可以为你的新数组提供这样的“部分”:

    pairs.push(initialArr.splice(0, 2))
    

    Juts 循环遍历您的初始数组 initialArr.length/2 次。

    Working demo

    编辑:或者你可以更新你的替换逻辑,不仅获取一个接一个的数字,还获取对(例如'-1.23568 75.87956,-1.75682 22.87694'),然后将其拆分两次。

    split(',') --> ['-1.23568 75.87956', '-1.75682 22.87694']
    

    然后循环和

    split(' ')
    

    【讨论】:

    • 感谢您的回复。我没有得到您的编辑答案,请您详细说明一下。
    • @chlara 检查请here
    【解决方案3】:

    你可以避免一些复杂的正则表达式逻辑,只要你有:

    const [a1, a2, b1, b2] = ["-1.23568", "75.87956", "-1.75682", "22.87694"]
    
    const result = [[a1, a2], [b1, b2]]
    

    或者如果有两对以上:

    const array = ["-1.23568", "75.87956", "-1.75682", "22.87694", "-1.33343", "3.34432"]
    
    const result = [];
    for(let i = 0; i < array.length; i+=2) {
      result.push(array.slice(i, i+2))
    }
    

    【讨论】:

    • 感谢您的回复。它奏效了。
    • 所有三个答案都对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多