gpt4 book ai didi

javascript - 如何实现循环额外条件

转载 作者:行者123 更新时间:2023-11-28 17:15:10 25 4
gpt4 key购买 nike

我试图实现一些非常简单的事情,但找不到正确的解决方案:如果在范围内找到,如何替换字符串中的符号,如果不在范围内,则如何保持它们“原样”。

    var BASE = "ABCDEFGHIJ"; 
var CODE = "0123456789";
var WORD = "DEKF" // K is out of range
var CONS = []; // result expected: 34K5

for (b=0; b<BASE.length; b++){

for (w=0; w<WORD.length; w++){

// if a sign of WORD is in BASE we change it with CODE equivalent: A->0
if(WORD[w]==BASE[b]) {
CONS.push(CODE[b]);
}

// if not we keep it in place
else {
// make sure the sign is out of BASE range
if(BASE.search(WORD[w]) == -1 ) {
CONS.push(WORD[w]);
break;
}
}
}
}

console.log(CONS.join(''))

控制台

without the else condition = 345 ( no K )
else cond without break = KKK3K4KK5KKKK
else cond with break = KKK3K4KKKKKK
else without if->match and without break = DEKFDEKFDEKF3EKFD4KFDEK5DEKFDEKFDEKFDEKF
else without if->match and with break = DDD3EDDDDDD
with continue instead of break = KKK3K4KK5KKKK

然后我尝试使用标签来打破循环:

    for (b=0; b<BASE.length; b++){

sign:
for (w=0; w<WORD.length; w++){

// if a sign of WORD is in BASE we change it with CODE equivalent: A -> 0
if(WORD[w]==BASE[b]) {
CONS.push(CODE[b]);
}

// if not we keep it in place:
else {
if(BASE.search(WORD[w]) == -1 ) { // make sure the sign is out of BASE range
CONS.push(WORD[w]);
break sign;
}
}
}
}

控制台

with sign label and break sign = KKK3K4KKKKKK
with sign label before the first loop and break sign; = K

最佳答案

提供替代方案。特别是如果列表变得更长并且为了可维护性,您可以使用 Map 而不是 2 个松散的字符串。(在下面的示例中, map 是从字符串创建的)

之后,您可以简单地将所有字符替换为 map 的条目或字符本身:

const BASE = "ABCDEFGHIJ", CODE = "0123456789", WORD = "DEKF",
codes = new Map([...BASE].map((b,i)=> [b,CODE[i]]));

let CONS = [...WORD].map(s=> codes.get(s) || s);

console.log(CONS.join(''));

关于javascript - 如何实现循环额外条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com