猿问

在Javascript中,当我分离字符串时,应该如何在拆分后为每个字符串运行该方法?

function processPathLettersIntoArray(source){

    source = source.split("M").join(";M");

    source = source.split("L").join(";L");

    source = source.split("z").join(";z");

    source = source.split(";");

    source = source.slice(1);

    return source.map(mapGroup);

}

这是我的分割方法。


function gcodeXY(source){

   var [xVal, yVal] = source.split(",");

   return `X${xVal} Y${yVal}`

}

let start="X0 Y0"; //another side effect :-(


function mapGroup(grp){

    let s=grp.split(" ");

    if (s[0]=="M"){

        start=gcodeXY(s[1]);

        last=s[1];

        return "G0 F200 "+start;

    }

    else if (s[0]=="L"){

        start=gcodeXY(s[1]);

        last=s[1];

        return "G1 F100 "+start;

    }

    else if (s[0]=="z"){

        last=s[1];

        return "G1 F100 "+start;

    }

    return grp;

}

这就是我希望分割后每个字符串的实现方式。


function path2gcode(source){

    source = processPathLettersIntoArray(source);

    return source;

}

这是我需要运行的方法。我想问的是,在Javascript中,当我分割字符串时,分割后的每个字符串应该如何运行该方法?图片显示了输入和输出示例以及我当前的输出。

https://img1.sycdn.imooc.com/652a77070001fe1209680628.jpg

回首忆惘然
浏览 86回答 2
2回答

白衣染霜花

这会起作用function processPathLettersIntoArray(source) {  const result = source.replace(/M/g, ";M").replace(/L/g, ";L").replace(/z/g, ";z").split(';').slice(1);  return result.map(mapGroup);}function gcodeXY(source) {   const [xVal, yVal] = source.split(",");   return `X${xVal} Y${yVal}`;}let start="X0 Y0"; //another side effect :-(function mapGroup(grp) {    let s = grp.split(" ");    if (s[0]=="M"){        start = gcodeXY(s[1]);        last=s[1];        return "G0 F200 "+start;    }    else if (s[0]=="L"){        start=gcodeXY(s[1]);        last=s[1];        return "G1 F100 "+start;    }    else if (s[0]=="z"){        last=s[1];        return "G1 F100 "+start;    }    return grp;}function path2gcode() {  const source = 'M 1,2 L 2,2 L 3,3 z';  return processPathLettersIntoArray(source);}

UYOU

这应该适合你function processPathLettersIntoArray(source){&nbsp; &nbsp; source = source.split("M").join(";M");&nbsp; &nbsp; source = source.split("L").join(";L");&nbsp; &nbsp; source = source.split("z").join(";z");&nbsp; &nbsp; source = source.split(";");&nbsp; &nbsp; source = source.slice(1);&nbsp; &nbsp; output = [];&nbsp; &nbsp; for(i=0;i<source.length;i++) {&nbsp; &nbsp; &nbsp; output.push(mapGroup(source[i]));&nbsp; &nbsp; }&nbsp; &nbsp; return output;}或者,.map可以使用&nbsp;function processPathLettersIntoArray(source){&nbsp; &nbsp; &nbsp; &nbsp; source = source.split("M").join(";M");&nbsp; &nbsp; &nbsp; &nbsp; source = source.split("L").join(";L");&nbsp; &nbsp; &nbsp; &nbsp; source = source.split("z").join(";z");&nbsp; &nbsp; &nbsp; &nbsp; source = source.split(";");&nbsp; &nbsp; &nbsp; &nbsp; source = source.slice(1);&nbsp; &nbsp; &nbsp; &nbsp; return source.map(mapGroup);&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答