Learning to parse the JSON string today, using an eval () method, why do I need parentheses when parsing a string? I can't touch my head. The original JavaScript {} statement block is ambiguous, without parentheses there will be errors, understanding this ambiguity is very helpful for us to understand JavaScript code.
Two meanings of one, {} statement blocks
Represents a statement block
A. You can use {} to enclose code in JavaScript to facilitate the administration of code in the editor. Because JavaScript does not have a block-level scope, this is harmless.
B. In JavaScript, conditional judgment statements, looping statements, and functions all require {} statement blocks to consolidate code
Object literal Amount
var box = {
name: ' Kuoaho ',
age:21
}
At this point [code] as an expression, you can assign a value to a variable
An object literal is an expression that can generate an object value
What happens if the object literal is not used as an assignment expression?
Example
{name: ' Kuoao '} No error, but no object
{name: ' Kuohao ', age} //Error
It can be seen from above that the object literal can only be assigned as an expression, the first is not wrong, but JavaScript interprets it as a label statement.
Analysis
{name: ' Kuoao '}
{} A statement block
//Name: ' Kuohao ', a label statement, used to mark the For loop
Three, but the problem comes again ...
{
name: ' Kuohao ',
age:21
}
So why do you have an error? Isn't this the literal writing of objects?
Because of the two semantics of {} in JavaScript, {} is not only considered an object literal but is also considered a block of code.
Analysis:
{
name: ' Kuohao ',
age:21
}
A code block, two label statements, if there is no comma, is completely no problem, so the key is the comma, two of the separation of statements should use semicolons, so JavaScript will determine that this is a syntax error
Four, the correct wording
({
name: ' Kuohao ',
age:21
})
//correct notation
() Converts a statement to an expression, called a statement expression, or is an object literal not an expression? Why do you need () to convert?
With parentheses, this ambiguity can be eliminated because the code in parentheses is converted to an expression evaluation and returned, so the statement block becomes an object literal, or it can be concluded that the object literal must exist as an expression