Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

ascii art - implement a function in javascript

I solved a problem in javascript, but When I execute the code I get a result which is:'A', but I would like to know if it is good what I coded because I have doubts. Here is the problem:

printChar allows to display one and only one ASCII character from A to Z (inclusive) on several lines and columns (graphic representation called "ASCII Art").

We want to perform the operation in the other direction: obtain a character from its representation graphic. Implement the scanChar (str) method so that it returns the character c associated with its representation graph (i.e. str = printChar (c)). If str does not match a character between A and Z (inclusive), then scanChar should return the character '?'

here is my code:

function scanChar(str) {
        
    // Iterate over each character from A to Z.
    for (var c = 'A'; c <= 'Z'; c++) {
        // Check to see if the character corresponds with the ASCII art.
        if (printChar(c) === str) {
        // Return the character if it does.
        return c;
        }
    }

    // Optionally use a '?' character to indicate that the string passed
    // doesn't correspond to any valid ASCII art.
    return  '?';

    }




    function printChar( s) {
    return "S";

}

var art=printChar('A');
console.log(scanChar(art));
question from:https://stackoverflow.com/questions/65649676/implement-a-function-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is elegant but has a number of logic problems that can be easily fixed.

  1. your prinbtChar function always returns the string "S"
  2. your for loop to go from A - Z isn't quite right. I've replaced it with one way to do this.

function scanChar(str) {
console.log(str)
        
    // Iterate over each character from A to Z.
    
    var first = "A", last = "Z";
    for(var i = first.charCodeAt(0); i <= last.charCodeAt(0); i++) {
         var c = String.fromCharCode(i);

  
        if (printChar(c) === str) {
        // Return the character if it does.
        return c;
        }
    }

    // Optionally a '?' character to indicate that the string passed
    // doesn't correspond to any valid ASCII art.
    return  '?';

    }




    function printChar( s) {
    return s;

}

var art=printChar('J');
console.log(scanChar(art));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...