First, you declare a new variable, out , within the anonymous function that you
ID: 3584902 • Letter: F
Question
First, you declare a new variable, out, within the anonymous function that you are creating. This variable will hold the reversed string.
You then begin a loop, starting at the end of the input string (remember that JavaScript string character indexing starts at 0, not 1, so you need to begin at this.length – 1) and decrementing one character at a time. As you loop backwards through the string, you add characters on at a time to your output string stored in out.
After you finish the following coding, save it as extendobject.htmla
<html>
<head>
<title>object oriented programming</title>
<script>
String.prototype.backwards = function() {
var out ='';
for(var i =this.length-1; i >=0; i --) {
out + = this.substr(i , 1);
}
return out;
</script>
</head>
<body>
</script>
var inString = prompt("enter your test string:");
document.write(inString.backwards());
</script>
</body>
</html>
Explanation / Answer
Rectified code:
<html>
<head>
<title>object oriented programming</title>
<script>
function reverseString(str) {
return str.split('').reverse().join('');
}
</script>
</head>
<body>
<script>
var inString = prompt("enter your test string:");
document.write(reverseString(inString));
</script>
</body>
</html>
Explanation:
- Logic is changed for the function
- close the script tag properly
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.