我有一个逗号分隔的字符串,我想把它转换成一个数组,这样我就可以遍历它。

有什么内置的功能吗?

例如,我有这个字符串

var str = "January,February,March,April,May,June,July,August,September,October,November,December";

现在我想用逗号将其拆分,然后将其存储在数组中。


当前回答

一个很好的解决方案:

let obj = ['A','B','C']

obj.map((c) => { return c. }).join(', ')

其他回答

一个很好的解决方案:

let obj = ['A','B','C']

obj.map((c) => { return c. }).join(', ')

最简单的方法:

let myStr = '1, 2, 3, 4, 5, 7, 8';

const stringToArr = (myStr) => {
    return myStr.split(',').map(x => x.trim());
};
var array = string.split(',');

MDN引用,对于极限参数的可能意外行为非常有用。(提示:“a,b,c”.split(“,”,2)指向[“a”,“b”],而不是[“a,”b,c“]。)

let str = "January,February,March,April,May,June,July,August,September,October,November,December"

let arr = str.split(',');

这将导致:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

如果要将以下内容转换为:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

这:

"January,February,March,April,May,June,July,August,September,October,November,December";

use:

str = arr.join(',')

如果用户通过添加额外的空格键入错误。你可以用这样的东西。

tags: foo,  zar, gar
const stringToArr = (string) => {
  return string.trim.split(",");
};