M.Barley M.Barley - 16 days ago 5
Javascript Question

How do i populate an array with the uni codes of characters within a string?

I have written a function with the intention of populating an array with uni code characters for each of the letters in a string.

However the result I am being returned is an array of null values.



function rot13(str) {
var splitString = str.split("");
var myArray = [];

for (var i = 0; i < splitString.length; i++) {
myArray.push(splitString[i].charCodeAt[i]);
}
return myArray;
}
console.log(rot13('cats'));




Answer

String.prototype.charCodeAt(n) finds the code of a character in position n the string. So instead of splitting the string, just iterate it:

function rot13(str) { 
  var myArray = [];

  for(var i = 0; i < str.length; i++ ) {
    myArray.push(str.charCodeAt(i));
  }
  
  return myArray;
}

console.log(rot13('cats'));