如何将逗号分隔的字符串转换为数组?

2020/09/21 13:31 · javascript ·  · 0评论

我有一个逗号分隔的字符串,我想将其转换为数组,因此可以循环遍历它。

有内置的功能吗?

例如,我有这个字符串

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

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

var array = string.split(',');

MDN参考,主要用于limit参数可能发生的意外行为(提示:"a,b,c".split(",", 2)出来的["a", "b"]不是["a", "b,c"]。)

请注意是否要针对整数,例如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
}

将返回一个包含整数而不是字符串的数组。

嗯,分割是危险的恕我直言,因为字符串始终可以包含逗号。请注意以下几点:

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 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;
}

返回功能

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/

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";

用:

str = arr.join(',')

这是一个将字符串转换为数组的函数,即使列表中只有一项(没有分隔符)也是如此:

function listToAray(fullString, separator) {
  var fullArray = [];

  if (fullString !== undefined) {
    if (fullString.indexOf(separator) == -1) {
      fullAray.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如果字符串中没有任何分隔符(仅一项),则会引发错误。

我遇到了类似的问题,但由于要将CSV文件转换成数组数组而变得更加复杂(每行是一个数组元素,内部有一个由逗号分隔的项目数组)。

最简单的解决方案(我敢打赌,更安全)是使用PapaParse,它具有“无标题”选项,可将CSV文件转换为数组数组,此外,它会自动检测到“,”作为我的分隔符。

另外,它是在Bower中注册的,因此我只需要:

bower install papa-parse --save

然后在我的代码中使用它,如下所示:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

我真的很喜欢它。

一个好的解决方案:

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

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

最短的

str.split`,`

您可以尝试以下代码段:

 var str = "How,are,you,doing,today?";
    var res = str.split(",");
    console.log("My Result:", res)

对于字符串数组,以逗号分隔的字符串:

let months = ["January","Feb"];
let monthsString = months.join(", ");

正如@oportocala提到的,空字符串不会导致预期的空数组。

因此,请执行以下操作:

str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)

对于期望的整数数组,请执行以下操作:

str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')
本文地址:http://javascript.askforanswer.com/ruhejiangdouhaofengedezifuchuanzhuanhuanweishuzu.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!