使用分隔符拆分字符串数组 [英] Split an array of strings using a separator

查看:108
本文介绍了使用分隔符拆分字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,是否可以使用分隔符将每个字符串拆分为多维字符串数组?我正在尝试使用字符串分隔符拆分多维数组的字符串,但我还不知道如何在不使用多个for循环的情况下迭代多维数组。

In JavaScript, is it possible to split each string in a multidimensional array of strings using a separator? I'm trying to split a multidimensional array of strings using a string separator, but I don't yet know how to iterate over a multidimensional array without using multiple for-loops.

var theArray = [["Split,each"],["string, in"],["this, array"]];

据我所知,无法应用字符串.split(,)多维数组的方法。我需要找到一种解决方法,因为此代码无效:

As far as I know, it isn't possible to apply the string.split(",") method to a multidimensional array. I'll need to find a workaround, since this code isn't valid:

alert([["Split,each"],["string, in"],["this","array"]].split(","));


推荐答案

使用数组 map 返回数组修改版本的方法:

Use the Array map method to return a modified version of your array:

var newArray = theArray.map(function(v,i,a){
   return v[0].split(",");
});

作为参数传递给地图的函数方法用于确定映射数组中的值。如您所见,该函数获取数组中的每个值,用逗号分隔它,并返回两个字符串的结果数组。

The function that is passed as the argument to the map method is used to determine the values in the mapped array. As you can see, the function takes each value in the array, splits it by comma, and returns the resulting array of two strings.

然后输出:

[["Split", "each"],["string", "in"],["this", "array"]];

为了使任意深度的数组递归递归,你可以使用:

To make this work recursively for arrays of arbitrary depth, you can use:

var newArray = theArray.map(function mapper(v,i,a){
    if(typeof v == "string"){
        return v.split(",");
    } else {
        return v.map(mapper);
    }
});

这篇关于使用分隔符拆分字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆