要求将str中的before字符串用after替换,after的首字母大小写要和before的一样:
function myReplace(str, before, after) { let arr=str.split(' '); let regex=/^[A-Z]/; if(arr.indexOf(before)){ if(regex.test(before)){ after=after[0].toUpperCase()+after.slice(1); } else{ after=after[0].toLowerCase()+after.slice(1); } arr[arr.indexOf(before)]=after; } return arr.join(' '); } console.log(myReplace("A quick brown fox Jumped over the lazy dog", "Jumped", "leaped"));//A quick brown fox Leaped over the lazy dog
要求返回DNA碱基对:
/*法一:function pairElement(str) { let arr=str.split(''); console.log(arr); for(let i=0;i<arr.length;i++){ if(arr[i]==='G'){ arr[i]=[arr[i],'C']; } if(arr[i]==='C'){ arr[i]=[arr[i],"G"]; } if(arr[i]==='A'){ arr[i]=[arr[i],'T']; } if(arr[i]==='T'){ arr[i]=[arr[i],"A"]; } } return arr; }*/ /*法二:function pairElement(str) { let matchWithBasePair = function(char, pairedArray) { switch (char) { case "A": pairedArray.push(["A", "T"]); break; case "T": pairedArray.push(["T", "A"]); break; case "C": pairedArray.push(["C", "G"]); break; case "G": pairedArray.push(["G", "C"]); break; } }; const paired = []; for (let i = 0; i < str.length; i++) { matchWithBasePair(str[i], paired); } return paired; } */ //法三: function pairElement(str) { var pairs = { A: "T", T: "A", C: "G", G: "C" }; var arr = str.split(""); return arr.map(x => [x, pairs[x]]); } //调用: console.log(pairElement("GCG"));//[ [ 'G', 'C' ], [ 'C', 'G' ], [ 'G', 'C' ] ] console.log(pairElement("ATCGA"));//[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]
。。。
标签:arr,after,console,log,练习,JS,str,一些,before From: https://www.cnblogs.com/168-h/p/16758420.html