【问题标题】:How to avoid elements in split function to be saved in an array?如何避免拆分函数中的元素保存在数组中?
【发布时间】:2017-06-06 11:17:23
【问题描述】:

我正在尝试在 javascript 中使用 split() 方法,并且将拆分的元素保存为我不想完成的数组。

我希望将元素保存为对象中的值。

var string = "as1234,as5678,as6789";
var result = {}
result.values = string.split(',');

我得到的输出如下:

  result{
values : ["as1234","as5678","as6789"]
}

我想要的输出是:

result{
values : "as1234","as5678","as6789"
}

【问题讨论】:

  • ...以及将使用哪些密钥来存储它们?
  • 您希望result 对象是什么?
  • 结果对象应该是这样的结果{values: "as1234","as4567","as6789"}
  • 你想要什么
  • split 返回一个数组,你想要的不是有效的语法,所以不确定你想要什么。

标签: javascript jquery arrays split


【解决方案1】:

假设您想要一个值用引号填充的字符串,您可以拆分字符串并将数组的每个元素字符串化,然后将其连接到一个字符串中。

var string = "as1234,as5678,as6789",
    result = {};

result.values = string.split(',').map(a => JSON.stringify(a)).join(',');
console.log(result);

或者如果模式一致,您可以使用正则表达式来获取组并相应地解析字符串。

var string = "as1234,as5678,as6789",
    result = {};

result.values = string.replace(/([a-z0-9]+)/g,"\"$1\"")
console.log(result);

【讨论】:

  • 这就是我在您的答案中添加的原因。但认为string.replace 会比split+map+join 更好,因此将您的答案作为综合答案。
猜你喜欢
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 2019-10-21
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多