Jump to content

Javascript Encode String


SparX

Recommended Posts

Hello everyone! I need someone to tell me what's wrong with this script:

function stringToArray(string){
			var sVector = [string.split];
			var iR;

			for (i=0;i<=sVector.length;i++)
				iR = sVector;
			
			return iR;

		}


		function stringEncode(string){
			var vector = string.split("");
			var iR;
			for (i=0;i<=string.length;i++){
				iR += string.charCodeAt(i);
			

			}return iR;
		}


			window.onload = function (){
				document.getElementById('clickButton').onclick = function(){
					alert(stringEncode(document.getElementById('textEr').value));
				}
			}

I try to define a function that encodes a simple string, but it returns "NaN" instead of numbers.

Thanks in advance.

Link to comment
Share on other sites

These are the problem:

i<=sVector.length

i<=string.length

 

There is no index equal to the length of the array or string. The last index is always one less than then length.

 

Aside from that, this is doing the exact same assignment over and over when you only need to do it once.

for (i=0;i<=sVector.length;i++)
                iR = sVector;

This creates an array with a single element in it which is a reference to a function:

var sVector = [string.split];

This is actually going to result in a single number rather than a string of numbers because you're doing a mathematical sum of the numbers.

for (i=0;i<=string.length;i++){
				iR += string.charCodeAt(i);
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...