0

I am writing a code to encode a string and it hopes to display the encoded string in a div. However, it shows nothing. May I know what's wrong with my code? Thank you.

HTML:

<div id="c"></div>

Javascript:

function encode() {
  var a = "abcde";
  a = unescape(a);
  var c = String.fromCharCode(a.charCodeAt(0) - a.length);
  for(var i = 1; i < a.length; i++){
    c += String.fromCharCode(a.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
  document.write(c)
}

2 Answers 2

1

You're writing the output to the document after returning from the function. Try something like this:

function encode (){
  var a = "abcde";
  a = unescape(a);
  var c = String.fromCharCode(a.charCodeAt(0) - a.length);
  for(var i=1; i<a.length; i++){
      c+=String.fromCharCode(a.charCodeAt(i) - c.charCodeAt(i-1));
  }
  return c;
}

document.getElementById("c").innerText = encode();
<div id="c"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

You're calling document.write() after your function has already returned. Thus, that line never executes.

Either:

  • Move the return to the end of the function
  • Have the calling code capture the return value and them it calls document.write()

1 Comment

No need to thank me. Simply up-vote answers that help, and click "accept" on the one that best solved your problem.

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.