如何在Javascript中附加或连接字符串?

所以我试图添加到一个字符串,它显示为空。


var DNA = "TAG";

var mRNA = "";


m_RNA()


function check(a, b, string) {

  if (string = a) {

    mRNA.concat(b);

  }

}


function m_RNA(){

  //console.log(DNA)

  for (var i = 0; i < DNA.length; i++) {

    console.log("Checking: " + DNA[i]);

    check("T", "A", DNA[i]);

    check("A", "U", DNA[i]);

    check("C", "G", DNA[i]);

    check("G", "C", DNA[i]);

    console.log(mRNA);

  }

}

它应该在控制台中显示AUC,但只是空白。顺便说一下,这是通过firefox实现的。


波斯汪
浏览 123回答 2
2回答

UYOU

mRNA.concat(b);不会改变字符串,它只会计算值。您需要mRNA = mRNA.concat(b)(或mRNA = mRNA + b)更改的值mRNA。

富国沪深

您可以考虑将任务包装到函数中,而不是尝试在上限范围内对变量进行突变。让我们对其进行重构,以确保m_RNA返回正确的映射:var DNA = "TAG";// create a map so every char maps to something.const map = {&nbsp; T: 'A',&nbsp; A: 'U',&nbsp; C: 'G',&nbsp; G: 'C',};// check only needs to pick from map, or return an empty string.function check(fragment) {&nbsp; return map[fragment] || '';}function m_RNA(dna) {&nbsp; // reduces all the chars to the new sequence&nbsp; return Array.from(dna).reduce(&nbsp; &nbsp; function (result, fragment) {&nbsp; &nbsp; &nbsp; return result.concat(check(fragment))&nbsp; &nbsp; },&nbsp; &nbsp; "",&nbsp; );}var mRNA = m_RNA(DNA);console.log('mRNA', mRNA);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript