使用多个三元运算符替换字符串的多个字符

Replacing multiple characters of a string using multiple ternary operators

我正在尝试解决 JavaScript 中的一个简单问题。我必须取一串字符并进行以下替换:

G -> C
C -> G
T -> A
A -> U

例如,如果输入是 ATCG,输出将是 UAGC

最初我想将字符串转换为数组,然后在其上使用map()。但是,既然可以在一次迭代中完成工作,为什么还要遍历字符串两次呢?

所以我寻找了其他方法,比如 RegExp,但似乎唯一的方法是进行多个替换 replace(),这确实会更加低效。

所以我想使用 for...of 然后我写了这段代码:

let s = 'ATGC*';

let r = '';

for(const x of s) r += x === 'C' ? 'G' : 'G' ? 'C' : 'T' ? 'A' : 'A' ? 'U' : '-NaN-';

console.log(r);

它似乎将 C 转换为 G 并将其他所有内容转换为 C

我认为它应该是这样工作的:

x ===    // if the current character is equal to
'C' ?    // `C` 
'G' :    // r += `G`
'G' ?    // else if it is equal to `G`
'C' :    // r += `C`
'T' ?    // else if it is equal to `T`
'A' :    // r += `A`
'A' ?    // else if it is equal to `A`
'U' :    // r += `U`
'-NaN-'; // else it is not a nucleotide

有人知道实际情况吗?

如果你真的喜欢三元组,你可以在多个条件下采用这种方法。

r += x === 'G'
    ? 'C'
    : x === 'C'
        ? 'G'
        : x === 'T'
            ? 'A'
            : 'U'

更好的方法是用一个对象来替换值。

nucleobases = { G: 'C', C: 'G', T: 'A', A: 'U' }

稍后替换为

r += nucleobases[x];

这个用一个三元就可以搞定,虽然意义不大,但是可以搞定。您需要对每个字母进行检查。

let s = 'ATGC*';

let r = '';

for (const x of s) r += 
  x === "G" ? "C" : 
    x === "C" ? "G" : 
     x === "T" ? "A" :
       x === "A" ? "U" : x;

console.log(r);

三元对于这个来说太复杂了。只需使用简单的对象查找即可。

var replacements = {
  G: 'C',
  C: 'G',
  T: 'A',
  A: 'U',
}

let s = 'ATGC*';

let r = '';

for (const x of s) r += replacements[x] || x;

console.log(r);

以及我将如何编码

const replacements = {
  G: 'C',
  C: 'G',
  T: 'A',
  A: 'U',
}

const s = 'ATGC*';

const re = new RegExp(`[${Object.keys(replacements).join('')}]`,'g');

const r = s.replace(re, x => replacements[x]);
console.log(r);