我有一个逗号分隔的字符串,想将其转换为数组,以便可以循环遍历。
是否有内置函数可以完成此操作?
例如,我有这个字符串:
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";
现在我想通过逗号将其拆分,并将其存储在数组中。
const array = string.split(',');
MDN 参考文档,对于 limit
参数可能出现的意外行为非常有帮助。(提示: "a,b,c".split(",", 2)
的结果是 ["a", "b"]
,而不是 ["a", "b,c"]
。)
string
具有一些Java String
的丰富性。 - Michael Shopsinarray
中有元素,则split
函数可以正常工作。但是,如果您从服务器/数据库中获取数据,则可能会遇到麻烦,因为''.split(',')
的长度为1,即['']
。 - Vlad Goran如果你的目标是整数,比如1、2、3、4、5等,请注意。如果你打算在将字符串分割后将数组的元素用作整数而不是字符串,请考虑将它们转换为整数。
var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");
加入如下循环:
for (a in temp ) {
temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}
将返回一个包含整数而非字符串的数组。
parseInt('010')
与 parseInt('010', 10)
进行比较。 - Álvaro Gonzálezmap
函数可用于在一行中完成整数解析:str.split(',').map(parseInt)
。 - Jud在我看来,split方法是很危险的,因为一个字符串中总是可能包含逗号。请看下面这个例子:
var myArr = "a,b,c,d,e,f,g,','";
result = myArr.split(',');
那么你会如何解释呢?你希望结果是什么?一个包含以下内容的数组:
['a', 'b', 'c', 'd', 'e', 'f', 'g', '\'', '\''] or
['a', 'b', 'c', 'd', 'e', 'f', 'g', ',']
(function($) {
$.extend({
splitAttrString: function(theStr) {
var attrs = [];
var RefString = function(s) {
this.value = s;
};
RefString.prototype.toString = function() {
return this.value;
};
RefString.prototype.charAt = String.prototype.charAt;
var data = new RefString(theStr);
var getBlock = function(endChr, restString) {
var block = '';
var currChr = '';
while ((currChr != endChr) && (restString.value !== '')) {
if (/'|"/.test(currChr)) {
block = $.trim(block) + getBlock(currChr, restString);
}
else if (/\{/.test(currChr)) {
block = $.trim(block) + getBlock('}', restString);
}
else if (/\[/.test(currChr)) {
block = $.trim(block) + getBlock(']', restString);
}
else {
block += currChr;
}
currChr = restString.charAt(0);
restString.value = restString.value.slice(1);
}
return $.trim(block);
};
do {
var attr = getBlock(',', data);
attrs.push(attr);
}
while (data.value !== '')
;
return attrs;
}
});
})(jQuery);
split() 方法用于将一个字符串分割成子字符串数组,并返回新的数组。
var array = string.split(',');
var sampleTags = ['vinita@itsabacus.com']; console.log(sampleTags); $("#order_id").on("change", function() { var order_id = document.getElementById('order_id').value; $.ajax({url: "model/getUserMailIds.php",data:{order_id:order_id},type:'POST', success: function(result){ alert(result); var sampleTags = result.split(',');; console.log(sampleTags); }}); });
- Vinita Pawarstr.split(',')
str.split(',')
这个简单的函数并没有太多智能性。以下是一些不同需求的升级版,您可以根据自己的需要来定制功能。
const str = "a, b,c, d ,e ,f,,g"
const num = "1, 2,3, 4 ,5 ,6,,7.495"
const mix = "a, 2,3, d ,5 ,f,,7.495,g"
console.log( str.split(',')
) // spaces NOT trimmed, empty values included
// ["a", " b", "c", " d ", "e ", "f", "", "g"]
console.log( str.split(/[ ,]+/)
) // spaces trimmed, empty values skipped
// ["a", "b", "c", "d", "e", "f", "g"]
console.log( str.split(/\s*,\s*/)
) // spaces trimmed, empty values NOT skipped
// ["a", "b", "c", "d", "e", "f", "", "g"]
console.log( num.split(',').map(Number)
) // numbers, empty values default to zero
// [1, 2, 3, 4, 5, 6, 0, 7.495]
console.log( num.split(/[ ,]+/).map(Number)
) // numbers, skips empty values
// [1, 2, 3, 4, 5, 6, 7.495]
console.log( mix.split(/\s*,\s*/)
.map(x => (x === '') ? '' : (isNaN(Number(x)) ? x : Number(x)) )
) // mixed values, empty values included
// ["a", 2, 3, "d", 5, "f", "", 7.495, "g"]
JSON.parse
虽然可能感觉有些像黑科技,但它非常简单,并且被大多数JavaScript引擎高度优化。
它还具有一些其他优点,例如支持嵌套列表。但是也有一些缺点,例如需要输入正确格式的JSON。
通过类似我在上面使用string.split
的方式,使用string.replace
可以修复输入。在下面的前两个示例中,我自定义了如何处理空值:
const num = "1, 2,3, 4 ,5 ,6,,7.495"
const mix = "a, 2,3, d ,5 ,f,7.495,g"
console.log( JSON.parse('['+num.replace(/,\s*,/,',0,')+']')
) // numbers, empty values default to zero
// [1, 2, 3, 4, 5, 6, 0, 7.495]
console.log( JSON.parse('['+num.replace(/,\s*,/,',')+']')
) // numbers, skips empty values
// [1, 2, 3, 4, 5, 6, 7.495]
console.log( JSON.parse('['+mix.replace(/(^|,)\s*([^,]*[^0-9, ][^,]*?)\s*(?=,|$)/g,'$1"$2"')+']')
) // mixed values, will ERROR on empty values
// ["a", 2, 3, "d", 5, "f", "7.495", "g"]
请注意以下内容:
var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);
将会发出警报1
将您的逗号分隔字符串传递到这个函数中,它将返回一个数组,如果未找到逗号分隔的字符串,则它将返回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;
}
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
'echo'.split(',')
返回 ['echo']
,''。split(',')
返回 ['']
。如果调用了 x.split(',')
且 x
不是字符串(包括 x
为 undefined 或 null 的情况),则会出错,因为其他类型没有可用的 split
函数。请注意保持原文意思,使翻译更通俗易懂。 - Joel Leesplit
。谢谢你指出来了... - Kabb5let 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"]
this:
"January,February,March,April,May,June,July,August,September,October,November,December";
使用:
str = arr.join(',')
var array = (new Function("return [" + str+ "];")());
它接受字符串和对象字符串:
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
var stringtext = "String, text, I, am"; var stringtextArray = (new Function("return [" + stringtext + "];")());
结果为:SyntaxError: Unexpected identifier。 - nycdanie
string.split(',');
- Braden Best