JavaScript beginner troubles with quotation marks

前端 未结 2 1514
长发绾君心
长发绾君心 2021-01-28 19:33

I\'m trying to learn JS from a book (Beginner JavaScript by Jeremy McPeak), but I\'m stuck with this code:



        
相关标签:
2条回答
  • 2021-01-28 20:06

    myString is a string. The function parseInt(string, radix) will parse a string as a integer (see this for more examples).

    The quotes are the way they are so that the output has the quotes displayed. If you don't want the quotes in the output the js could be simplified to:

    document.write(myString + " is " + parseInt(myString, 10) + " as an integer" + "<br/>");
    

    but this wouldn't be as clear in showing how parseInt works.

    0 讨论(0)
  • 2021-01-28 20:31

    In Javascript (and most other languages), you write a string by putting a sequence of characters between a pair of quote characters. So a string containing abc is written as

    "abc"
    

    If you want one of the characters in the string to be a quote character, you have to escape it, so it won't be treated as the end of the string. So a string containing abc"def would be written as:

    "abc\"def"
    

    This is demonstrated in your code where it has

    "\" is "
    

    This is a string that begins with a literal quote followed by the word is.

    If you want a string containing only a quote character, you need to put an escaped quote between the quotes that indicate that you're writing a string:

    "\""
    

    That's what's at the beginning of the concatenation expression in your code.

    If you just wrote

    \"
    

    that would be an escaped quote. But since it's not inside quotes, it's not a string -- it's not valid syntax for anything.

    In Javascript, there's another option. It allows both single and double quotes to be used to surround a string. So if you have a string containing a double quote, you can put it inside single quotes:

    '"'
    

    You don't need to escape it because the double quote doesn't end a string that begins with single quote. Conversely, if you want to put a single quote in a string, use double quotes as the delimiters:

    "This is Barry's answer"
    
    0 讨论(0)
提交回复
热议问题