ECMASCRIPT-Js data types, operators, process control, function scope chain, pre-resolution, anonymous function self-execution, and weird places

Source: Internet
Author: User
Tags case statement hasownproperty

1. javascript is a weak type language, not non-type. There are two types of js types: 1: undefined, null, boolean, string, number, object; 2: undefined, boolean, string, number, object, function. I personally admire the second type. On the one hand, it is because the saying that everything is an object will confuse beginners. On the other hand, the function is a very huge thing that needs to be discussed separately. 2. in js, there will be implicit type conversion during operator operations, and js has a particularly strong fault tolerance capability, allowing a variety of weird writing methods, which will make some 'js cool ss ', this is also the reason for triggering various tricks and tricks. In 2.1 js, there is only one string on both sides of the plus sign, so this expression is executed according to the string link, 3 + '4' => 34; 3 + 4 => 7; but note that: 3 + 4 + '5' => 75; here, according to the priority, the first plus sign will normally be added by number; 7-'3' => 4; in js, implicit type conversion is performed to enable normal expression calculation for the types on both sides of the left and right. (Note: => indicates that the result of the preceding expression is the following one, not greater than or equal to the number) 2.2 = It must be of the same type before it can be equal (all equal ), under this premise, the basic type =; and the object and function type must be the same reference to be equal, such as var obj = {a: 3 }; obj ==={ a: 3} // false. = implicit type conversion can be performed during determination. 3 = new Number (3) // true; '33' = 33; // true = 1; // true false = 0; // The toString and valueOf methods of the true object and the string or numeric type are used, but the object ratio is rarely used. The Switch/case statement is compared by =. For example, Switch (3) {case '3': // code} won't pass case. 2.3> and <both comparison operators are normal numeric comparison, both strings are compared by Unicode Code, are boolean type, true> false, are compared by the valueOf method of objects; to compare a number with a string, the string must be converted to a number before comparison. Otherwise, false is returned in any case, 3 <'4' // true 3 <'4a '// false 3> '4a' // false; Comparison between numbers and boolean, true to 1, convert false to 0 for comparison; Convert string to boolean for comparison; convert true to 'true' for comparison; Convert false to 'false' for comparison; Convert string to object for toSting, generally, basic types and objects are not compared. 2.4 In some special cases, null = undefined // true NaN = NaN // false (determined by isNaN) typeof null // object null instanceof Object // false 3 instanceof Object // false new Number (3) instanceof Object // true typeof NaN // number {}=={}// false var str = '12a'; typeof str ++; // The str value of number is NaN, ++, and + =, which are not fully equal (typeof results are all lowercase strings) 2.5 [] = true // false [] = flase // true if ([]) {} [] & true // true [] indicates false when compared with true or false, but other operations, such True is displayed in the if statement. Null, undefined, 0, "", NaN are directly expressed as false. 3. Js flow control except General if/else switch/case for/while? There is also a for/in for in loop which is generally used in unordered objects. in general, the for/in performance is not very good and should be avoided as much as possible. Another tag is different from other languages, the tag is a small scope of goto statement, which is effective in the scope of js (that is, the function). The purpose is to jump out of multiple loops or to determine whether to use tags, the program itself has problems, and I personally feel that there is no need to use it. 4. in js, only functions have independent scopes (except for the eval escalation scope). The scope chain is for variable access, the scope chain is only related to the Function Definition. when accessing a variable, the js engine will find this variable in the current function scope, if it cannot be found, it will go to the scope of its parent function. In this way, if the function at the outermost layer is not found, it will be found on the window object. If it is not found, an error will be reported, this is the scope chain. The scope chain is also related to an important concept-closure. When a sub-function references the variables of the parent function, if the sub-function is always accessible (return out, window or other object attributes), the memory space of the parent function will not be released, which is the closure. 5. pre-resolution refers to advance the declaration of functions and variables to the top of the scope. The pre-resolution of var-form variables/function declarations is equivalent to dividing var aaa = 3 into var aaa; aaa = 3; two statements, and advance the previous one to the top of the scope, function pre-resolution is to advance the entire function declaration to the top of the scope, the functions declared in the main var form are parsed in two parts. 6. anonymous function self-execution, function () {} () has a syntax error, you can write it as (function () {} () or (function (){})(), in fact, this is just for the syntax separation, in fact ~ Function () {} () or + function () {} () are all possible. 7. In js, the color is the hex value used in ie, that is, the value you assign. FF and Chrome use rgb, red, blue, so if you want to use the color value in js for some judgment operations, all use the rgb value for uniformity. The browser does not support uniformity of red, blue, and pink. (Except for testing) 0.1 + 0.2! = 0.3 computers cannot accurately represent most decimal places. 0.1 is not really 0.1. Therefore, decimals are generally added or subtracted. For example, a + B is replaced by (100 * a + 100 * B)/100, the number of zeros after 100 indicates the precision. To compare decimals, for example, a + B = c, replace 9 with a + B-c <0.000001. in js, undefined has a special meaning, but it is not a reserved word. In ie (only tests earlier versions), the undefined value can be rewritten, for example, undefined = 'abc '; var a; a = undefined; // false 'aac '+ undefined // aacabc. Of course, this is only in ie. Advanced browsers do not exist. Therefore, in jquery source code, undefined is passed in as a parameter to prevent tampering with the undefined value, but no one will do this 10. '10 13 21 48 52 '. replace (/\ d +/g, function (match) {return parseI Nt (match) <30? '*': Match;}) // *** 48 52 the regular replace method can accept the callback function. The parameter is the matched value (a string ), return is replaced. To match multiple global matches, g 11. in the function, the variable name is duplicated, var value is assigned, function declaration> function parameter> var Declaration (pre-resolution ). the order here is irrelevant to the declared position. For example, function fun1 (a) {var a = 3; function a () {} alert (a)} fun1 (222); 3 is displayed; function fun1 () {var a; function a () {} alert (a)} fun1 (222), the result is the function popped up; function fun1 (a) {var a; alert ()} fun1 (222); the result is 222. Here, regardless of the order, only function parameters and variable names or function names have the same name, as long as there is a change, the variable value is the value of arguments [0] 12. javascript is case-sensitive. It is case-insensitive in HTML. Therefore, attribute names in html can be uppercase or lowercase, but javascript must be 13 in lowercase. the comments in js are // code or/* code */html: <! -- Code --> css annotation:/* code */14. return {a: 3}; if the json behind the function is not in a line with return, the final result of the function is undefined, because the last statement in each line of js statements can be added without extra points, the js engine will help you add them, but it is best to add them to facilitate compression and readability. 15. obtains the attributes of an object. [] getAttribute, which is a non-standard attribute in html. It is filtered by chrome and other advanced browsers. Therefore, getAttribue is used to obtain the attribute, but it cannot obtain []. attribute of the value assignment. You can only obtain the custom attribute and the attribute set by sertAttribute in html. each basic type has a packaging type, such as 'abc '. in fact, js will convert the string to its packaging type, and then look at its length attribute. it itself has no attribute. After the call, the temporary object will be destroyed, alert (1.abc) is incorrect, but alert (1 ). abc), undefined 17.var str = '33aaa3 '; str. toUpperCase (); the result is '33aaa3 ', but the str value is '33aaa3'. If you think that the toUppercase () function will not change the string itself, it will return a result, many methods of strings, such as replace The method will not change the string itself. If you want to use the final generated value, it is best to save a copy, but the array pop, push and other methods will change the array itself. 18. 33/0 // infinity-332/0 // infinity 0/0 // NaN 19. in js, control statements such as for/if/swicth/try do not have a separate scope, although the Declaration has a pre-resolution. However, one method is incompatible. if (22> 14) {function aaa () {alert (1) }}else {function aaa () {alert (2 )}} aaa (); aaa () is pop-up 1 under FF, other browsers pop-up 2. therefore, try not to declare a function in the if statement. if you really want to declare a function, write it as var aaa = function () {// code. As mentioned above, the result of var declaration, function declaration, and function name duplication is displayed. In js, theoretically, only function scopes are available. Remember that this and the variables in the real parameters in the function are the places where this function is executed. For example: var ddd = {ccc: 'abc', aa: function () {function bb (aaaa) {alert (aaaa);} bb (this. ccc) ;}} this. ccc = 333; ddd. aa. call (window); bb (this. ccc); this is in the execution environment of the aa function. Here is the window, and the result is 333 if it is replaced with ddd. aa (). The result is 'abc' 20. the scope chain and the prototype chain are the search variables, the prototype chain is the search object attribute, the scope chain is only related to the function definition, and the this in the function is only related to the function execution. Prototype chain is related to inheritance. Sub-objects can access parent-level attributes and Methods 21. [aa (), 3 + 5, 2]; function aa () {return 33;} is not written at all. every element of the array can be an expression, but it is generally used, first, save the function value with a variable. In the array, the variable can be used. 22. new Object (), new Date (); this bracket can be omitted if no parameter exists, for example, new Object and new Date can both be used. This indicates that it is an Expression 23. delete obj. attr child instanceof parent delete and instanceof are all operators. Although the variables declared by var are properties on the window object, delete cannot be deleted, however, you can delete the file without the var statement in the advanced browser (ie cannot be deleted ). Generally, the custom attributes of a custom object can be deleted, while those defined by the system cannot be deleted. ???????? 24. & | in js is short-circuited. If a & B is false, B will not execute. If a is true, the result of a & B is the value of B. Note that a & B will not convert the Boolean values of a and B before calculation. If a is true, a & B is the value of B, not the Boolean value corresponding to B, if (g () & [] =! []) Should be treated as if (g () & []) =! []). Assume that g () is true, so (g () & []) is equivalent to (true & []). The result is [] not true ,! The result of [] is false, so if judgment can be simplified to: [] = false. Compared with Boolean values in js, there is a strange phenomenon (as mentioned earlier). Likewise: [] =! [] Is true.} So the if condition is true. Therefore, the if statement is used. A ++ and a + = 1 are different. 25. eval () setInterval ('alert (33) ', 30), new Function (''), the latter two can use the eval Function in disguise, but try not to use it like this, however, one of the points in js is That ajax and jsonp have to eval the string and convert it into a real js statement. SetInterval is a historical issue. 26. a> B? Result1: result2, a conditional operator. The result is a number or a separate expression. Do not use a few, separate expressions. This method reports an error. typeof is an operator, the priority is relatively high. If there is an operation, use parentheses as much as possible. 27. switch (n) {case num: // code; case num2: // code; default: // code;} both n and num can be variables or expressions, but must be =, that is, the type must be the same '3' and 3 are not equal. 28. although the for (var key in obj) {obj [key]} for in loop is unnecessary, for example, arrays are enumerated in the push order, however, the efficiency of for in is very low. In addition, some attributes of an object cannot be enumerated. HasOwnProperty: used to determine whether an object has an attribute or object with the name given by you. However, you must note that this method cannot check whether the property exists in the prototype chain of the object. The property must be a member of the object. Therefore, if you want to for the in object itself, use if (obj. hasOwnProperty (key) 29. tag statements are used in combination with if and for statements. They cannot be used by a single statement. tag: if (a> B) {// code break tag;} jumps out of the if loop, in a loop, use jumps out of the loop. continue jumps out of this loop for multi-layer nesting, which is of little significance and the label statement is only valid in the current function scope. 30. throw new Error ('error, haha '); throws an Error, which is the same as a statement running Error. Try {// code} catch (ex) {alert (ex)} finally {// code, sometimes, when users encounter accidental errors caused by operations and are eager to get online, they can be put in try first. A try can have multiple catch, rarely used, and rarely used finally. 31. The with (obj) {} statement will add the obj object to the top of the scope. It will be used only when the prefix is long, but it is better to store the prefix with variables. Generally, you do not need 32. debugger. If you do not need to play anything, you can use debugger to conveniently view where the statement is executed. Incompatible. Used for debugging. 33. 'Use strict 'strict mode. 'Use strict' is only a string, but it must appear at the beginning of the script or at the beginning of the function. In strict mode, a lot of things are disabled. For example, with is disabled, simple function execution, this is not a window but undefined, and parameters with the same name will fail, the arguments and parameters are changed to the same reference. (Nima, it's so sad that I wrote so much in the morning and didn't save it.) 34. ES5 provides an unstandard attribute _ proto __for accessing the prototype of an object, but obj is generally used. constructor. and constructor is correct. 35. the object serial number actually refers to the conversion of an object into a string, which is the same in turn. However, the interactive data in the front and back ends is generally in json format, so serialization/deserialization is generally for json, ES5 defines two new methods, JSON. stringify (json1)/JSON. prase (json2) is serialized and deserialized respectively. in fact, as long as the for/in loop, eval is also easy to achieve serialization/deserialization 36. creating a new object a = new Arrar (5) in the Array is to create five empty elements, instead of creating a 5, and there is no [] intuition. Therefore, it is generally unnecessary to create a new Array. Pop/push/unshift/shift: Just remember to clear the array and use arr. length = 0. delete arr [3] is actually setting an undefined value with arr [3. Does not change the length, array traversal for (var I = 0, len = arr. length; I <len; I ++) Only accesses the length attribute at a time. In particular, when the pseudo array of the dom object is accessed, reducing the number of dom accesses can improve the performance, the types of array elements can be different, but js does not provide a direct method for multi-dimensional arrays. But you can use the join method: join arr. join ('-'), that is, use-to connect each string. Arr. reverse sorts arr in reverse order. Arr. sort (function (a, B) {reutrun a-B;}) is a sorting method. The parameter is two elements. You can process two elements first. For example, you can make the string lowercase first, in comparison, the return positive number is arranged by a and B, and the negative number is arranged by B and. arr. slice (num1, num2) intercepts an array composed of num1 and num2 elements. If the negative number is from the array forward,-1 is the last element. If there is only one parameter, it is at the end of the array, but the second parameter is not included. Arr. splice (num1, num2), splice not only returns an array consisting of num1 and num2, but also deletes this segment in the array arr, arr. concat method, array connection, multiple parameters, single element and array. Methods In ES5, such as forEach, map, and indexof, are easy to implement. The interview may ask questions about other methods except forEach. Pop/push/unshift/shift/splice/reverse/sort and other methods to modify the original array, join/concant/slice is not modified, if you do not remember whether to modify, use a variable to save the result. Some pseudo arrays sometimes need the Array method. You can use Array. prototype. concat. call (obj, obj2); but generally it is not necessary to use this method. Sometimes the results are quite strange. Not every pseudo array, every method can be used in this way. 37. Number of function name. length parameters in function, and number of arugments. length parameters. The callee and caller attributes of arguments all fail in strict mode. The caller attribute value of arguments is the function that calls this function. The callee value of arguments is the function itself and is often used for recursion. 38. if you need to define a variable that is not reset for static function execution, do not use a global variable or function name. attribute name = 3; it is OK, but it is generally defined outside the function and can be accessed by using the closure. Call/apply are all functions on the prototype. The first parameter is to assign a value to this. call is followed by a bunch of parameters, and apply is an array of 39. A instanceof B true if A can access B's prototype. Determines whether a variable is a string (typeof arr) = 'string' | arr. constructor = String is actually the basic type of arr. constructor also has a value. str is also a String, so arr is used directly. constructor = String can be judged, and the same is true for arrays. 40. regular Expression: [] indicates any one of [], which can also be \ w. In addition to the characters in [], uppercase is the opposite of lowercase, and \ s is any blank character, \ w digits or letters. \ D number. Any character except the line break Terminator ,? 0/1 times, + 1 or multiple times, * 0 or multiple times, {n, m} At Least n times not exceeding m times, {n,} At Least n times, {n} n times, | yes or. [AB] can be written as a | B, but [] can be [a-B]. This range can be used in regular expressions. Brackets can be used in regular expressions, to match parentheses, escape them. /^ $/Indicates that the start and end I are case-insensitive, g is a global match, and the string method is 'javascript '. the second parameter of replace (/javascript/gi, 'javascript ') can be a function, as mentioned in 1.7. The replace method does not change the string itself, as long as the returned value. The 'ff df jj J'. split (/\ s/) split parameter can also be a regular expression. The return value of str. match (/\ d/) is an array of matched strings. Reg. test (str) and reg.exe c (str) if the regular expression is g Global, each matching will not start from the beginning, such as/\ w /. test ('AB') returns false when it is executed for the third time. Therefore, do not add g when using these two methods. The exec result is an array of matched results. Null is not matched. 41. using only one var to declare variables is helpful for compressing code.

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.