1

我有一串看起来像这样的数据

0E-11 GERBER CA 960350E-110.0215.500000000 0E-12 TEHAMA CA 960900E-11214.800000000

我想将此字符串转换为数组数组。

请注意,每 4 个元素后,该数组应划分为新数组,最终结果应如下所示:

期望结果:

this.tblData: Array(2)
            0: ["0E-11,"GERBER", "CA", "960350E-110.0215.500000000"]
            1:["0E-12", "TEHAMA", "CA" ,"960900E-11214.800000000"]

谢谢

4

3 回答 3

2

您可以在该字符串上使用余数运算符和 forEach 循环来构建数组数组,其中每个嵌套数组每n步创建一次:

var result = [];

"0E-11 GERBER CA 960350E-110.0215.500000000 0E-12 TEHAMA CA 960900E-11214.800000000".split(" ").forEach(function(element, index, array) {
  if( (index + 1) % 4 === 0) {
    result.push([
      array[index-3],
      array[index-2],
      array[index-1],
      array[index]
    ]);
  }
});

console.log(result);

于 2017-10-11T23:51:49.927 回答
2

不需要使用模运算符,只需将循环的计数器增加 4:

var original = [
    '0E-11',
    'GERBER',
    'CA',
    '960350E-110.0215.500000000',
    '0E-12',
    'TEHAMA',
    'CA',
    '960900E-11214.800000000'
];

var result = [];

for (var i = 0; i < original.length; i += 4) {
    result.push([
        original[i],
        original[i+1],
        original[i+2],
        original[i+3],
    ]);
}

console.log(result);

输出:[ [ '0E-11', 'GERBER', 'CA', '960350E-110.0215.500000000' ], [ '0E-12', 'TEHAMA', 'CA', '960900E-11214.800000000' ] ]

这假设数据是 4 个元素对齐的。

于 2017-10-12T00:08:22.403 回答
2

您可以reduce用于此类目的

let result = "0E-11 GERBER CA 960350E-110.0215.500000000 0E-12 TEHAMA CA 960900E-11214.800000000"
  .split(" ") // split the string based on the spaces
  .reduce((current, item) => { 
    if (current[current.length - 1].length === 4) {
      // in case the result array has already 4 items in it
      // push in a new empty array
      current.push([]);
    }
    // add the item to the last array
    current[current.length - 1].push(item);
    // return the array, so it can either be returned or used for the next iteration
    return current;
  }, [ [] ]); // start value for current would be an array containing 1 array

console.log(result);

它首先用空格分割你的字符串,创建一个值数组,然后我们可以使用reduce函数转换结果。

reduce函数将第二个参数作为当前参数的起始值,该参数将作为一个包含 1 个空数组的数组开始。

在 reducer 内部,它首先检查数组中最后一项的长度是否为 4,如果是,则将下一个子数组添加到数组中,然后将当前项推入最后一个数组中。

结果将是一个包含您的数组的数组

于 2017-10-11T23:58:37.533 回答