JavaScript interview Slot Hui: commas, colons, and parentheses

Source: Internet
Author: User
Tags eval json

  After reading the JavaScript data types and expressions and operator-related knowledge that you can his experiment a JavaScript pen question, I did not expect to die again and again in commas, colons and parentheses, we have to look at these symbols.

  Comma comma Our common usage is to declare some variables in a row, a lot less var     var a=1,     b=2,     c=3; Method arguments we use commas to separate the object properties from the comma   ' function fbn (name,title) {} var person={name: "Byron", Age: "24"}; "However we will also encounter the problem of the comma   1 var a= (1,2,3) appearing in the assignment expression; The reference to the comma operator in expressions and operators corresponds to this case, when the expression evaluates to the last subexpression, which is 3. Don't misunderstand. The preceding subexpression does not execute, and each subexpression executes, except that "return value" is the last expression result.     VAR a,b; A= (b=1,2); Console.log (a);//2 Console.log (b);//1 colon?: operator   var p=gender? ' Male ': female; Object literal     var obj={    Name: "Byron",     age:24}; Switch statement     switch (t) {    Case 1:         console.log (' xxx ');     &NBS P   break;     Case 2:         Console.log (' ooo ');         break; I believe this is a familiar use, then we can a topic   1 x:y:z:1,2,3; Will the above operation not error? What is the result of a no error operation? A lot of students will be surprised to see this for the first time, think it will be wrong, but the result is 3, to see why   in fact, the colon also has a role: Declaration Label,javascript statement can have a tag prefix, we call it a tag statement, Break or continue can be used in conjunction with tagged statements, controlling the flowRide. If the label is duplicated, an error occurs. Our above statements can be translated into this     x:  y:   z:1,2,3 So we combine the knowledge of the comma just said to understand why the result is 3, many optimization recommendations are not advocating the use of labels, do not think of the C-language Goto, Using the Label control process makes the program quite difficult to read.   VAR x=1; foo:{    x=2     break foo;     x=3; Console.log (x); Curly Braces Object Direct amount declaration     VAR obj={    Name: "Byron",     age:24}; The entire statement causes the assignment statement, the right value part 10 expressions, constructs an object   function declaration or the function direct quantity by the direct quantity     function fn1 () {     //...} <br> var fn2=function () {   /...}; I believe this usage is not closed.   Organization compound statement     with (obj) {   //...} for () { //...} if () {   ///...} }else{   /...} curly braces do not bring block-level scopes the classmate familiar with JavaScript is certainly familiar with this, although curly braces can organize complex statements and so on, it refers to the same "block", with even provides a similar function, But unfortunately so JavaScript only function scope, no block scope, and then JavaScript in the following procedure will declare global variables, this little knowledge point is often cited hero bow   use declaration variables outside of function (whether or not to use Var) In a function, it is not directly assigned to the Window property   Var a=2 with var declaration variable; function fn () {    b=3     window.c=4;} In addition to these three types of variables that are part of the function range, in many JavaScript specificationsIt is mentioned that the variable is declared as early as possible because it does not have a block scope     function fn (n) {    if (n>1) {        var a=n; &nb Sp  }else{        var b=n;    }     Console.log (a); Such code has syntax errors in many languages, because if and else curly braces have block scopes, variables A and B are inaccessible in their respective block scopes. But in JavaScript, there is no block scope, so we can still access the variable Console.log declared in if or else, which is really a bad design, in order to reduce the likelihood of error, try to advance the variable declaration.   Many written questions are the     {a:1} for this knowledge. var x={a:1}; {A:1,b:2}; var y={a:1,b:2}; Trying to find out for yourself is surprising, we analyze   {a:1} JavaScript has legendary "statement precedence", which is when the curly braces can be understood as a compound statement block can also be understood as the object's direct volume, JavaScript will interpret it as a compound statement quickly. {a:1} is actually a:1, think about the role of the colon is not know why the return value is 1.   var x={a:1} when {a:1} appears as the right value, it is not a statement, but a direct expression, so the curly braces are treated as Object direct volume syntax, and the result is an object.   {a:1,b:2}; See above this is simple, can be translated as: A:1,b:2 combined with commas and colon function, the result seems obvious, is 2. However, in fact, the error, this is why? After the comma operator must be an expression, and the label statement 10 label statement, is a statement, so the error.   Understand this knowledge let's try a few more questions (see the answer on the console, don't try to alert)   {foo:[1,2,3]}[0]; {a:1}+2; 2+{a:1}; Do not know that the small partners did the right, the core of these topics, the braces, although it does not appear to have any effect, but the role of the statement separator, {foo:[1,2,3]}[0] can be understood as     {foo:[1,2,3]}; [0]; So the return value is [0], same {a:1}+2 becomes     {a:1}; +2 but! Why 2+{a:1} is not the same? In this case, the addition operator causes the plus sign to be left bound, {} is resolved to an expression (must be added by the expression), based on the data type knowledge Object {a:1} converted to Nan   parentheses there are several usages in JavaScript brackets   function declaration or call expression parameter table   This good understanding, the function of the definition of the time need to use parentheses to wrap its parameters, separated by commas, when the call is the same as     function fn (name,age) {   /...} fn (' Byron ', 24 ); var f=new fn (' Byron ', 24) and some keyword constituent conditional statements   Our common if, switch, and while parentheses are the     if (a>0) {   //. .. while (I<len) {   //...} for (Var i=0;i<len;i++) {   //...} group operators the grouping operator can only contain an expression, and may change operator precedence. Discard some of the possible syntax trees, the most common     var x= () 1+2) *3; Believe that there is no need to explain, many students will think that the parentheses have the function of force expression, in fact, the one-sided understanding, this is only the change of operator precedence, generate a new syntax tree results. For a simple JSON string to object, because of browser compatibility reasons, can not use the JSON object, and lazy to introduce json2, so will use eval () processing, probably written like this     var jsonstr= ...; var jsonobj=eval (' + jsonstr + '); Many students will ask, why do I have to add a parenthesis? As we explained above, the format of the JSON string "{A:1,b:2}" is understood as a statement, which is the legendary label statement, the syntax tree is such   {a:1, b:2}   As mentioned above, the comma operator cannot be followed by the label statement, so an error occurs, with parentheses followed by the grouping operatorCan only contain an expression, so {} becomes a direct amount of syntax, which is what we want.   function expression called immediately to look back at what we call an immediate execution function, there are generally two ways of writing   (function () {}) (); (function () {} ());!function () {} (); Search a lot of information, finally saw the explanation, summed up, first of all we need to understand the function expression and function declaration difference, the ECMAScript specification definition is quite vague: the function declaration must have the identifier (Identifier) (is commonly called the function name), function expressions can omit this identifier:   function declaration:   Function functions name (parameters: optional) {function Body}   function expression:   function function name (optional) (parameter: optional) { function Body}   In fact, our common distinction is based on context, if the function fn () {} appears as a right value (right of the assignment expression), which is the expression, otherwise the function declaration. There are several seemingly unconventional ways that require our attention   new function fn () {}; expression, because in the new expression (function () {} ());//The expression, in the grouping operator so that we can understand the second way, is to use the group operator to change the syntax tree. The third way of writing, in fact, is to take advantage of the principle of a unary operator followed by an expression, and we can write a     +function () {} ()-function () {} () ~function () {} ().     (function () {} ()); (function () {}) (); [function () {} ()]; ~ function () {} ();! function () {} (); + function () {} (); -function () {} (); Delete function () {} (); typeof function () {} (); void function () {} (); The new function () {} (); New FuNction () {}; var f = function () {} (); 1, function () {} (); 1 ^ function () {} (); 1 > function () {} (); So we should call the function expression that immediately executes the function as an immediate call!   Bracket is relatively the simplest symbol, there are generally several semantics   * Array related   We know that arrays can be directly instantiated by means of parentheses (    var a=[1,2,3]; * Get object property value   This is also a common usage     var a=[1,2,3]; var b={name: ' Byron '}; A[2]; b[' name ']; See some interesting little topics     [1,2,3,4,5][0..tostring.length];//0. Equivalent to 0.0 ' foo '. Split (") + [];
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.