This article mainly introduces detailed information about the {} statement block in javascript. For more information about how to parse the json string, see the next tutorial. an eval () method is used, why should we add parentheses when parsing strings? Confused. In the original javascript, the {} statement block has two meanings, and errors may occur without parentheses. Understanding this ambiguity is of great help for us to understand javascript code.
I. Two meanings of {} statement Blocks
Statement Block
A. You can use {} In javascript to include the code and facilitate code management in the editor. This method is harmless because javascript does not have block-level scope.
{//some code...}
B. In javascript, condition judgment statements, loop statements, and functions all require {} statement blocks to integrate code.
Object literal
var box = { name:'kuoaho', age:21 }
// In this case, [code] is used as an expression and can be assigned to a variable.
// Actually, the object literal is an expression that can generate object values.
2. What happens if the object literal volume is not used as a value assignment expression?
Example:
{Name: 'kuoao'} // No error is reported, but no object {name: 'kuohao', age} // error is created.
From the above we can see that the object literal can only be assigned as an expression. The first method is correct, but javascript parses it as a label statement.
Analysis:
{Name: 'kuoao'} // {} A statement block // name: 'kuohao', a label statement used to mark the for Loop
3. But the problem is coming again ......
{name:'kuohao',age:21}
// Why is an error reported? Isn't this an object literal?
Because of the ambiguity of {} in javascript, {} is considered not only an object literal but also a code block.
analysis: { name:'kuohao', age:21 }
A code block contains two label statements. If there is no comma, there is no problem at all. Therefore, the key lies in the comma. Use a semicolon to separate the two statements. Therefore, javascript will determine that this is a syntax error.
4. Correct writing
({Name: 'kuohao', age: 21}) // correct statement
() Converts a statement into an expression called a statement expression. Isn't the object literal an expression? Why do I still need () for conversion?
After brackets are added, this ambiguity can be eliminated, because the code in the brackets will be converted into expressions to evaluate and return, so the statement block will become the object literal, it can also be concluded that the object literal must exist as an expression.