天天看點

Cocos Creator讀取配表/解析Csv檔案

Cocos Creator讀取配表/解析Csv檔案

網上解析csv文檔較少,CCC可以先使用 cc.loader.loadRes讀取csv檔案。然後讀到系統中是一串字元串。

再調用下方代碼通過正則解析成數組。再存到程式數組中即可使用。

//CSV轉Array

CSVToArray( strData, strDelimiter ) {
    strDelimiter = (strDelimiter || ",");
    var objPattern = new RegExp(
        (
            "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
            "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
            "([^\"\\" + strDelimiter + "\\r\\n]*))"
            ),
        "gi"
    );
    var arrData = [[]];
    var arrMatches = null;
    while (arrMatches = objPattern.exec( strData )){
        var strMatchedDelimiter = arrMatches[ 1 ];
        if (
            strMatchedDelimiter.length &&
            (strMatchedDelimiter != strDelimiter)
            ){
            arrData.push( [] );
        }
        if (arrMatches[ 2 ]){
            var strMatchedValue = arrMatches[ 2 ].replace(
                new RegExp( "\"\"", "g" ),
                "\""
            );
        } else {
            var strMatchedValue = arrMatches[ 3 ];
        }
        arrData[ arrData.length - 1 ].push( strMatchedValue );
    }
    if(arrData.length>0){
        arrData.pop();
    }
    return arrData;
},