JavaScript Learning Notes 1_ basics and common sense

Source: Internet
Author: User
Tags access properties string to number

1. Six types of data

5 Base: undefined,null,boolean,number,string (where Undefined derived from Null)

1 Complex: Object (essentially a set of unordered key-value pairs)

2. String to Number
    • Number (str): The first value is re-converted (valueof and then ToString is not the same as Nan), generally with our expected results are different, such as number (") =number (false) =number (null) =0 and VAR x; Number (x) =nan ... So it's generally used in the following two ways

    • parseint (str): can be specified in the system, it is recommended to use parseint (x, 10), such a format, which always indicates the binary

    • Parsefloat (str): Cannot specify a binary, returns an integer instead of a floating-point number when parsing an integer

3. Get the string length

A value of type string has the Length property. Str.length returns the string length integer value instead of the string length through other functions.

4. Value passing and address passing

Function arguments are value passing

5. Scope Chain

The essence is a stack, storing the variable object of each layer (similar to the compiler's symbol table pointer stack), the variable object holds all the variables and functions of the layer access permissions, if the layer is a function, then the variable object is a arguments object, the top of the stack is the executing context of the corresponding variable object, The bottom of the stack is the variable object that corresponds to the global execution environment.

6. Scope

There is no block-level scope, there is a function scope

7.2 Ways to create object objects
    1. var obj = new Object (); obj.attr = value;

Traditional way of calling constructors to create objects

    1. var obj = {attr1:value1, attr2:value2} or var obj = {"Attr1″: value1," Attr2″: value2}

Object literal notation, property name can be a string

Attention:

    1. Unless the attribute name is ambiguous, for example: null, VAR, and so on, do not use a string for the property name, of course, just a custom constraint

    2. When an object is defined with an object literal, its constructor is not called

8. Two ways to access attribute values
    1. Obj.attr

    2. obj["attr" advantage is the ability to access properties through variables such as var attrname = "attr"; Obj[attrname] more flexible

9. Declaration and initialization of arrays
    1. var arr = new Array (value1, value2 ...);

    2. var arr = Array (...); You can omit the new

    3. Array literal: var arr = [Value1, value2 ...];

Note: When you define an array with an array literal, its constructor is not called

10. Array-related functions

See appendix

11. The difference between a function declaration and a function expression
    1. function Fun () {...} The JS engine generates the object when the source code is loaded

    2. var fun = function () {...} The JS engine does not generate the functions object until it executes

12. Function overloading

Overloading is not supported. The function declared later overrides the first declaration, essentially assigning multiple assignments to the function name (just a pointer variable)

13. Special properties Inside functions
    1. The Arguments.callee function pointer to the function that owns the arguments object, that is, the current function

    2. This is a reference to the current execution environment, and the top-level this is the window

    3. Arguments.callee.caller function pointer, pointing to the function that called the current function, not returning NULL

Note: This can be an object reference or a function reference, but callee and caller can only be function references

14. Properties and methods of function objects
    1. The length function expects the number of named parameters, JS can pass any number of parameters to the function, because in addition to formal parameters, you can also use arguments to get any parameter

    2. Prototype a prototype object that points to a function

    3. Call (context, arg1, arg2 ...) is used to invoke a function in a specific scope and to unbind the object from the function.

    4. Apply (context, arguments, or other array object) functions as above, supports array parameters

    5. Bind/unbind (context, arg1, arg2 ...) bind/Unbind execution Environment or parameters, you can generate new functions from existing functions, but binding with BIND is not valid (consecutive! = multiple times), for example:

      + View Code

      The above code output ' Objdata ', ' objdata ', ' Newobjdata ', the second bind failed, because the BIND function is implemented internally by call, and the effect of a continuous binding is similar to:

      + View Code

      The second binding gets a function within fun1 that does point to newobj, but FUN1 does not use this at all, so there is no effect

15. Some common sense
    1. This always points to the object to which you belong (the property of who you are, and who you are inside)

      + View Code

      The above code outputs 1 and 2, because after executing the penultimate sentence, Obj2 adds a fun property with a value of obj1.fun reference, but because Obj2.fun is a obj2 property, this point points to obj2

    2. Define member functions on the constructor prototype as much as possible, because functions defined directly in the constructor have the overhead of a run-time closure

    3. Single quotes should be used in JS, because there are only double quotes in JSON and XML, and single quotes to avoid escaping

    4. Try to initialize the variable declaration at the same time as possible to differentiate the undefined representation from being declared. Because the typeof operator will return "undefined" for declared but uninitialized variables and undeclared variables

    5. Nan (not a number) is not equal to any value, including Nan itself, so you need to use the isNaN () function to determine

    6. You can add properties dynamically to values of reference types only. Adding a property to a value of a base type does not give an error but it doesn't make any sense

    7. The array will grow automatically based on the index. It is important to note that the length property is writable, which means that the array lengths can be set dynamically, such as truncation of trailing elements

    8. The function name is just a pointer variable. Function fun{...} fun = null; only the reference relationship is broken, the body is not destroyed

Appendix 1: Underlying Data types
    1. Undefined the default value of an object that has been defined but not initialized

    2. Null represents an empty object pointer, so it is detected with TypeOf to return an object

    3. Boolean Boolean value, note the Boolean () conversion function, with the following rule:

      1. True/false ~ No change

      2. Non-empty string/empty string ~ True/false

      3. Not 0 digits/0 and Nan ~ true/false

      4. Any object/null ~ true/false

      5. Undefined ~ False

      These rules are important because the IF condition automatically applies a Boolean () conversion, and if (obj) is common in JS code, and many times process control errors are caused by an if condition auto-conversion

    4. Number value, JS in +0 and 0 equal, note nan, it is not equal to anything, including itself, and it is neither greater than n nor less than or equal to N. The number variable supports the toString () function, which can be used to convert a numeric string, such as var num = 17;num.tostring (16) back to "11″

    5. String string, note the immutability of strings, and make a huge concatenation operation should use array + join instead of Loop +

Properties and methods for 2.Object type variables
    1. Constructor Save a reference to this constructor

    2. hasOwnProperty (Porpertyname) is used to check whether the current object has a specified property (where "property" includes properties and methods)

    3. isPrototypeOf (obj) is used to prototype a current object that is not a specified object

    4. propertyIsEnumerable (PropertyName) is used to detect whether a specified property can be enumerated

    5. toLocaleString () is equivalent to the ToString () function, but the region feature is attached

    6. ToString () returns the string representation of an object

    7. ValueOf () returns the string, numeric, or Boolean representation of an object

3. Common reference types
  1. Function JS is also an object, very flexible, such as:

    + View Code
  2. The
  3. Array type has the most action function for the

    1. Stack square function: push () Inserts an entry at the end of the array, POPs () tail out of the stack

    2. Queue function: Push () ibid., Shift () first dollar Out of the team and return to the first element; Unshift ()/pop ()

    3. Sort function: Sort (fun) no parameter comparison string ascending, with ladies incoming custom comparison function return positive/negative/0;reverse () Reverse order

      Note: sort ()/reverse () changes the original array directly, and the sort () default implementation is less scientific, and the result of sorting [1, 3, 10, 5] is [1, 10, 3, 5], and you must pass in a custom comparison function if you want to think about it.

    4. Action function:

      1. Arr.concat (arr1, arr2 ...) joins form a new array

      2. Arr.slice () equals subst The ring intercepts the string and uses the same

      3. Arr.splice () to insert items into the middle of the array, splice (StartIndex, num, item1, item2 ...) Indicates that the NUM entries starting with startindex are replaced with individual items, and only the first two parameters indicate that the NUM entries starting from startindex are changed to null (that is, delete), and the delete/replace/insert operation can be implemented with splice.

        Note: The splice function also changes the original array directly.

    5. Positional functions: indexOf (value) and LastIndexOf (value), finding the index position of value, no return-1, internally using the congruent operator (= = =)

    6. The
    7. Iteration function: Every (), filter (), ForEach (), map (), some () are all running the specified method for each item in the array, ie9+ support and not commonly used, where the narration is not expanded

    8. Attribution function: Reduce (), reduceright () No introduction, same reason as above

  4. Date type: Slightly more relevant, see W3school

  5. RegExp type: var regex =/^cat$/i; create regular Expressions (regexp type), supported modes are G, I, M represent global mode, ignore case mode, multiline mode. Of course, you can also use new RegExp (Strregex, Strmode), but why do you have to use it this way?

    JS supports regular capture, var matches = regex.exec (text); by Matches[0], matches[1] ... To get the captured content

    Normal regular match: regex.test (text) returns True/false

  6. Basic Package Type: boolean,string and number, have been meeting all the time, just did not notice, for example:

    + View Code

    The above code is equivalent to:

    + View Code

    Automatic packing and unpacking, in order to make the underlying data type easier to use, it is important to note that the new string () is different from the string () conversion method, which returns the type of object, which returns the string type, and because of this difference, mixing can cause unnecessary trouble. So there's no reason to explicitly create a wrapper type. Boolean,number is similar to it.

JavaScript Learning Notes 1_ basics and common sense

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.