Tim18318741662
无奈白了少年头
2017-05-16 08:08

Js如何快速切割字符串

  • javascript

RT,有这么一个字符串

 var mStr = 'total:week7:30;week6:30;week5:30;week4:30;week3:30;week2:30;week1:30;;count:week7:5;week6:2;week5:1;week4:3;week3:5;week2:4;week1:3;'

目标是切割成两个数组

 total =  ["30", "30", "30", "30", "30", "30", "30"]
 count = ["3", "4", "5", "3", "1", "2", "5"]

我自己的方法是这样的

 function splitStr(e) {
    var i = 0, j = 0
    var mData1 = e.split(';')
    var mData2 = new Array()
    for (i = 0; i < mData1.length; i++) {
        mData2[i] = mData1[i].split(':')
    }
    var mArray1 = new Array()
    var mArray2 = new Array()
    var k = 0
    for (i = 0; i < 7; i++) {
        k = 0
        for (j = 0; j < mData2.length; j++) {
            var checkStr = 'week' + (i + 1)

            if (mData2[j][0].indexOf(checkStr) != -1) {
                if (k == 0) {
                    mArray1[i] = mData2[j][1]
                    k = 1
                }
                else {
                    mArray2[i] = mData2[j][1]
                }
            }
        }
    }
    for(i = 0; i < 7; i++){
        if(isNaN(mArray1[i])){
            mArray1[i] = 0
        }
        if(isNaN(mArray2[i])){
            mArray2[i] = 0
        }
    }
    console.log(mArray1)
    console.log(mArray2)
}

我的问题就是有没有更加快速的方法来进行切割,或者对这个方法进行优化

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐

换一换