我有一个逗号分隔的字符串,我想把它转换成一个数组,这样我就可以遍历它。
有什么内置的功能吗?
例如,我有这个字符串
var str = "January,February,March,April,May,June,July,August,September,October,November,December";
现在我想用逗号将其拆分,然后将其存储在数组中。
我有一个逗号分隔的字符串,我想把它转换成一个数组,这样我就可以遍历它。
有什么内置的功能吗?
例如,我有这个字符串
var str = "January,February,March,April,May,June,July,August,September,October,November,December";
现在我想用逗号将其拆分,然后将其存储在数组中。
当前回答
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(',')
其他回答
请注意:
var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);
将提醒1
一个很好的解决方案:
let obj = ['A','B','C']
obj.map((c) => { return c. }).join(', ')
我编写了php脚本来将字符串转换为数组,您可以将其运行到浏览器中,因此很容易
<form method="POST">
<div>
<label>String</label> <br>
<input name="string" type="text">
</div>
<div style="margin-top: 1rem;">
<button>konvert</button>
</div>
</form>
<?php
$string = @$_POST['string'];
if ($string) {
$result = json_encode(explode(",",$string));
echo " '$result' <br>";
}
?>
下面是一个函数,它将字符串转换为数组,即使列表中只有一项(没有分隔符):
function listToAray(fullString, separator) {
var fullArray = [];
if (fullString !== undefined) {
if (fullString.indexOf(separator) == -1) {
fullArray.push(fullString);
} else {
fullArray = fullString.split(separator);
}
}
return fullArray;
}
这样使用:
var myString = 'alpha,bravo,charlie,delta';
var myArray = listToArray(myString, ',');
myArray[2]; // charlie
var yourString = 'echo';
var yourArray = listToArray(yourString, ',');
yourArray[0]; // echo
我创建这个函数是因为如果字符串中没有分隔符(只有一个项目),split会抛出一个错误。
将逗号分隔的字符串传递到此函数,它将返回一个数组,如果找不到逗号分隔字符串,则返回null。
function splitTheString(CommaSepStr) {
var ResultArray = null;
// Check if the string is null or so.
if (CommaSepStr!= null) {
var SplitChars = ',';
// Check if the string has comma of not will go to else
if (CommaSepStr.indexOf(SplitChars) >= 0) {
ResultArray = CommaSepStr.split(SplitChars);
}
else {
// The string has only one value, and we can also check
// the length of the string or time and cross-check too.
ResultArray = [CommaSepStr];
}
}
return ResultArray;
}