【问题标题】:Add single quotes in a string array javascript在字符串数组javascript中添加单引号
【发布时间】:2022-01-07 16:52:24
【问题描述】:

我一直在寻找解决方案,但找不到...

我有以下数组,输出如下:

['Fruits, Cars, Clothes, Shoes']

但我需要那个数组来输出以下内容:

['Fruits', 'Cars', 'Clothes', 'Shoes']

我已经尝试了以下方法,但没有成功:

var output= arr.map(item => "'" + item + "'").join();

你能帮忙吗

【问题讨论】:

  • arr[0].split(", ")
  • 那么字符串是如何进入到以字符串而不是数组开头的格式的呢?你能修复产生那条线的原因吗?
  • 来自API,我无法直接更改。

标签: javascript arrays quotes single-quotes


【解决方案1】:

只需获取数组的第一个(也是唯一的)项,然后是 split 它和 trim 每个元素:

const arr = ['Fruits, Cars, Clothes, Shoes'];

const newArr = arr[0].split(',').map(x => x.trim());

console.log(newArr);

【讨论】:

  • 注意:这仅在所有项目中都没有, 时才有效:['foo, foo,bar, bar'] 之类的东西会给出[ 'foo', 'foo', 'bar', 'bar' ]
  • 是的,显然,我认为分隔符是 , 而不是 ,
  • 谢谢!那行得通
猜你喜欢
  • 1970-01-01
  • 2023-01-13
  • 2013-03-09
  • 2016-03-08
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
相关资源
最近更新 更多