Strange results returned from String.slice() method

  • A+
Category:Languages

My case is to separate a string into array of strings and then convert every three characters into a string. ( e.g. "xxxyyy" -> ['xxx','yyy'] )

const translate = function (RNA) {     var arrRna = Array.from(RNA);     var arr = [];     for (var key in arrRna) {         if ((key % 3) == 0) {             var temp = RNA.slice( key,  (key+3));             arr.push(temp);         }      }     return arr; }  console.log(translate('xxxyyyzzz'));

Expected result : ['xxx','yyy','zzz']

But the result that I want is : [ 'xxx', 'yyyzzz', 'zzz' ]

Also, I noticed that the slice method works as expected in first iteration but after that, the weird result --> 'yyyzzz'. Why??

 


Tada! Rather than converting the string to an array and going through each character waiting for the index to be a multiple of 3, simply count by 3s.

function translate(rna) {   let arr = [];      for (let i = 0; i < rna.length; i += 3) {     arr.push(rna.slice(i, i + 3));   }      return arr; }  console.log(translate('xxxydyyzzzd'));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: