0

This is a bit maddening. New to javascript and I haven't coded in ages. I am looking to convert a string of characters into their charCodes and dump them into an array. This is the current code:

function fillArray(str) {
var arr=[];

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

    arr.push(str.charCodeAt(str.charAt(i)));
  }

  return arr;
}

What ends up happening is if I sent it a string like "abcd", it will return [97,97,97,97]. Even though the charAt(i) should be iterating through, the array only seems to be formed by looking at the first character in the string only. What am I missing?

3 Answers 3

2

charCodeAt takes the index of the character you want, not the actual character; so just remove the charAt part:

arr.push(str.charCodeAt(i));
Sign up to request clarification or add additional context in comments.

2 Comments

but why he is getting 97 all time
@Mahi because he's passing the return value from .charAt() as the index to be used by .charCodeAt(). It'll generally evaluate to NaN, which charCodeAt() accepts as equivalent to 0.
1

As T.J. Crowder pointed out, String.prototype.charCodeAt() takes an index as a parameter. The reason you're getting 97 all the time is (from MDN):

if it [the parameter] is not a number, it defaults to 0.

So it always takes the first letter (with index 0), which is "a" and its char code is 97.

Comments

0

You could split your string in an array (dumping) and map each character with its ascci code (transfarmation expected). This way, you would write it shortly in JS :

var fillArray = str => str.split("").map(x => x.charCodeAt(0));
console.log(fillArray("bonjour le monde"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.