javascript - 替换二维数组中的字符串
问题描述
我刮了一个网页,它有一张桌子。我像这样返回数组:
[
[
'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);
有人可以帮助我吗?
解决方案
您已经使用内部循环遍历内部数组中的字符串.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);
推荐阅读
- android - 视图内的 RecyclerView 页面指示器
- javascript - 将数据从 Chrome 扩展弹出窗口保存到速率受限的后端
- javascript - change() 不是函数
- visual-studio-code - 带有 Jupyter 交互窗口的 VS Code:如何更改 Python 交互窗口中的语法颜色(某些文本在深色主题上不可读)?
- unity3d - 在单个场景中关闭多人连接
- java - 无法初始化 com.ebay.sdk.SdkAPIInterfaceServiceLocator JAVA 类
- syntax - 使用多个匹配项时是否有更简单的方法来绑定整个匹配项?
- flutter - Flutter/Dart:自定义底部导航栏高度
- python - Sqlalchemy 方言 DATERANGE 与 psycopg2.extras.DateRange 变化界限
- html - 如何通过自定义引导设置下拉按钮的宽度?