问题
I'm trying to learn JS from a book (Beginner JavaScript by Jeremy McPeak), but I'm stuck with this code:
<script>
var myString = "56.02 degrees centigrade";
document.write("\"" + myString + "\" is " + parseInt(myString, 10) +
" as an integer" + "<br/>");
</script>
The result in html is this: "56.02 degrees centigrade" is 56 as an integer
.
What I don't understand is not explained in the book - why is this code written as it is? Could someone please explain in layman's terms why do we begin with "\""
(why not just \"
since that's escape sequence for double quotes), why after that we have to write "\"
(shouldn't it be just \"
if we want closing quotation marks for myString), and why is this written after that: is "
? Basically, that first part really confused me.
回答1:
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"
回答2:
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.
来源:https://stackoverflow.com/questions/31062544/javascript-beginner-troubles-with-quotation-marks