【问题标题】:How to convert string in to Array in NodeJs如何在 NodeJs 中将字符串转换为数组
【发布时间】:2020-08-23 07:46:20
【问题描述】:

我有这个字符串:

    var d = [
    '[(not set),20200409,103,0.0]',
    '[(not set),20200410,112,0.0]',
    '[(not set),20200411,56,0.0]',
    '[(not set),20200412,58,0.0]',
    '[(not set),20200413,108,0.0]',
    '[(not set),20200414,91,0.0]'];

但是我想要这种类型的数组通过转换字符串d 处理后的样子。

    var processd_array = [
     ['(not set)',20200409,103,0.0],
     ['(not set)',20200410,112,0.0],
     ['(not set)',20200411,56,0.0],
     ['(not set)',20200412,58,0.0],
     ['(not set)',20200413,108,0.0],
     ['(not set)',20200414,91,0.0] ];

如何在 Nodejs 中做到这一点?

【问题讨论】:

  • 你应该展示你已经尝试过的东西。见stackoverflow.com/help/how-to-ask
  • 您的字符串语法错误,并且在处理数组语法后也是错误的。您在错误的地方使用了反引号!

标签: javascript arrays node.js string


【解决方案1】:

首先让我们将d 数组中的每个元素拆分为多个片段。

var d= [
  '[(not set),20200409,103,0.0]',
  '[(not set),20200410,112,0.0]',
  '[(not set),20200411,56,0.0]',
  '[(not set),20200412,58,0.0]',
  '[(not set),20200413,108,0.0]',
  '[(not set),20200414,91,0.0]'];
 
const result = d.map(item => item.split(','));

console.log(result);

这可行,但它不会从每行的开头和结尾删除[] 字符。

让我们解决这个问题:

var d= [
  '[(not set),20200409,103,0.0]',
  '[(not set),20200410,112,0.0]',
  '[(not set),20200411,56,0.0]',
  '[(not set),20200412,58,0.0]',
  '[(not set),20200413,108,0.0]',
  '[(not set),20200414,91,0.0]'];

// remove [] characters from a string  
const removeUnwantedCharacters = str => str.replace(/(\[|\])/, '');

const result = d.map(item => item.split(',').map(removeUnwantedCharacters));

console.log(result);

【讨论】:

  • 感谢您的清晰解释,尽管问题很不清楚
  • 感谢 Ervin 的回答,您建议的解决方案对我有用。
猜你喜欢
  • 2020-11-04
  • 2020-08-13
  • 2015-11-11
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 2021-06-27
相关资源
最近更新 更多