首页 > 解决方案 > 替换二维数组中的字符串

问题描述

我刮了一个网页,它有一张桌子。我像这样返回数组:

[
  [
    'Veículo',
    'Entrega\nSem/Com oco\nQtde',
    'Entrega\nSem/Com oco\nKg',
    'Com oco Kg\n%'
  ],
  [
    'AAA3B43',
    '0 / 29',
    '0 / 1.712',
    '100\n100\n100\n '
  ],
  [
    'BBB8922',
    '0 / 22',
    '0 / 1.170',
    '100\n100\n100\n '
  ]
];

我的数组比这个大,它有很多列,有空字段。我只发布了必要的。

然后,我想返回相同的数据,但将\n替换为| 保存在文本文件中并在此之后进行处理。

我尝试了下面的代码,但这不起作用。


var oldArray = [
  [
    'Veículo',
    'Entrega\nSem/Com oco\nQtde',
    'Entrega\nSem/Com oco\nKg',
    'Com oco Kg\n%'
  ],
  [
    'AAA3B43',
    '0 / 29',
    '0 / 1.712',
    '100\n100\n100\n '
  ],
  [
    'BBB8922',
    '0 / 22',
    '0 / 1.170',
    '100\n100\n100\n '
  ]
];

var newArray = new Array;

oldArray.forEach((lines, index) => {
  lines.forEach((childLines, childIndex) => {
    newArray.push(lines.map(function(item){
      return item.replace(/\r?\n|\r/g,'|');
    }));
  });
  
});

console.log(newArray);

有人可以帮助我吗?

标签: javascript

解决方案


您已经使用内部循环遍历内部数组中的字符串.forEach(),因此无需使用 对这些字符串执行另一次迭代.map(),相反,您可以更新您的.push()方法以仅推送更新字符串值:

newArray.push(childLines.replace(/\r?\n|\r/g,'|'));

如果您从不使用它们,您的回调也不需要接受索引参数,只传递元素也可以:

var oldArray = [[ 'Veículo', 'Entrega\nSem/Com oco\nQtde', 'Entrega\nSem/Com oco\nKg', 'Com oco Kg\n%' ], [ 'BTT3B43', '0 / 29', '0 / 1.712', '100\n100\n100\n ' ], [ 'EKV8922', '0 / 22', '0 / 1.170', '100\n100\n100\n ' ]];

var newArray = [];
oldArray.forEach(lines => {
  lines.forEach(childLines => {
    newArray.push(childLines.replace(/\r?\n|\r/g,'|'));
  });
});

console.log(newArray);

或者,如果您愿意,可以使用.map(),这可能更合适,因为您想创建一个新的映射值数组:

const oldArray = [[ 'Veículo', 'Entrega\nSem/Com oco\nQtde', 'Entrega\nSem/Com oco\nKg', 'Com oco Kg\n%' ], [ 'BTT3B43', '0 / 29', '0 / 1.712', '100\n100\n100\n ' ], [ 'EKV8922', '0 / 22', '0 / 1.170', '100\n100\n100\n ' ]];

const newArray = oldArray.map(
  lines => lines.map(childLines => childLines.replace(/\r?\n|\r/g,'|'))
);

console.log(newArray);


推荐阅读