Some important points of Javascript basics

Some important points of the basic part

1. Write the location

  1. Can be written in the attribute of the tag

    <button onclick = "alert("点我")"></button>
    
  2. Can be written in the href attribute of a hyperlink

    <a href = "javascript:alert('点我')"></a>
    
  3. Written in a script note

    <script>
        alert('点我')
    </script>
    
  4. You can import external js files, which are imported through script tags. Generally, external files are imported, so you cannot write code in them. Even if you write them, the browser will ignore them. If necessary, you can create a new script tag for writing internal code.

    <script type = "text/javascript" src="js/script.js">
    	alert('我是猪')   //无效
    </script>
    



2. Syntax Notes

  1. Every statement in JS starts with () at the end, if you do not write a semicolon, the browser will add it automatically, but it will consume some system resources, and sometimes, the browser will add a wrong semicolon, so the semicolon must be written in development
  2. JS ignores multiple spaces or newlines, so we can format the code with spaces or newlines



3. Literals and variables

introduce

Literals: All are immutable values, and literals can be used directly. But we generally don't use it directly

Variable: It can be used to save literals, and the value of the variable can be changed arbitrarily. The variable is more convenient to use, so it is generally used during development.Store a literal in a variable, and rarely use literals directly




4. Data Types

introduce

The data type refers toliteraltype

There are 6 data types in JS:

  1. String String
  2. Number value
  3. Boolean Boolean
  4. Null empty value
  5. Undefined Undefined
  6. Object object

Among them, String, Number, Boolean, Null, and Undefined are all basic data types, and Object is a reference data type.



4.1 String

  1. In JS strings need to be enclosed in quotes, useapostropheorDouble quotesYou can, but don't mix it up
  2. Quotes cannot be nested, single quotes cannot be placed within single quotes, and double quotes cannot be placed within double quotes, butSingle and double quotes can be nested
  3. In the string we can use == ( \ )== as escape character, when expressing some special symbols, we can use '\' to escape
    • \n means newline
    • \t means tab character
    • \\ Express\


4.2 Number

introduce

  1. All numeric values ​​in JS are of type Number, including integers and floating point numbers (decimals)

  2. You can use an operator typeof to check the type of a variable. When checking a string, it returns a String, and when checking a value, it returns a Number

  3. If the represented value exceeds the maximum value, an Infinity is returned,Infinity is a literal representing infinity, and checking Infinity with typeof will also return Number, Infinity means positive infinity, -Infinity means negative infinity

  4. NaN is a special number that means Not a Number,Checking for NaN with typeof also returns Number

  5. The operation of integers in JS can basically guarantee the accuracy. If you use JS to perform floating-point calculations, you may get an inaccurate result, such as 0.1+0.2. Therefore, you must not use JS for operations that require relatively high accuracy.



4.3 Null、Undefined

introduce

  1. There is only one value of type Null, which is null. The value of null is specially used to representan empty object, when using typeof to check for null values, it will returnObject
  2. There is only one value of the Undefined type, which is undefined. When declaring a variable, butdoes not assign values ​​to variables, his value is aundefined, when using typeof to check for null values, it will returnUndefined


4.4 Coercion to String

  1. Method 1: Call the toString() method. Note that the two values ​​of null and undefined do not have the toString() method. Calling their methods will report an error.
  2. Method 2: Call the String() function. For Number and Boolean, it is actually calling the toString() method, but for null and undefined, it will not be called, and the conversion can be successful.


4.5 Casting Number

  1. String to Number: Use ==Number()== function
    • A string of pure numbers, directly converted to the corresponding number
    • If the string contains non-numeric content, convert to NaN
    • If it is an empty string or a string with all spaces, it will be converted to 0
  2. Boolean value to Number: use ==Number()== function, true is converted to 1, false is converted to 0
  3. null to 0
  4. undefined to NaN
  5. Specifically for dealing with strings:
    • parseInt(): converts a string to an integer
    • parseFloat(): Convert a string to a floating point number, he can get a valid decimal
    • For non-String use parseInt() or parseFloat(), it will first convert it to String and then operate


4.6 Other base numbers

introduce

  1. In JS, if you need to represent a hexadecimal number, you need to start with 0x
  2. If you need to represent octal numbers, you need to start with 0
  3. If you want to represent a binary number, you need to start with 0b, but not all browsers support it
  4. Strings like 070, some browsers will parse as octal, and some will parse as decimal
  5. Can be passed in parseInt()second parameter, to specify a base of the number


4.7 Convert to Boolean

Using the Boolean() method

  1. number ----> boolean: all except 0 and NaN are true
  2. string ----> boolean: all except the empty string are true
  3. Null and undefined ----> boolean: false
  4. object is also converted to true



5. Arithmetic operators

introduce

  1. When performing operations on non-Number values, these values ​​will be converted into Numbers and then operated. Any value and NaN operation will be NaN . If the addition operation is performed on two strings, it will be concatenated and the two characters will be combined. String to do a concatenation operation.
  2. Adding any value to a string will first convert it to a string , and then do a concatenation operation with the string. We can use this feature to convert any data type + a " " to a String, which is a kind of Implicit type conversion, done automatically by the browser, in fact it is also called String
  3. Except for the addition of strings, the rest of the operations are converted to Number



6. Immediately execute the function

<script>
    (function (){
    
    
        console.log('111')
    })()
</script>



7. Scope

7.1 Global scope

  1. Variables declared with the var keyword are declared before all code is executed
  2. A function created with a function declaration will be created before all functions are executed , so we can call it before the function declaration: function A(){}, but a function created with a function expression will not, var a = functionA(){}
  3. In the global scope, the created variables are saved as properties of the window object


7.2 Function scope

  1. When a variable is manipulated in the function scope, it will first look for it in its own scope. If there is one, it will be used directly. If not, it will look for the upper-level scope until it finds the global scope. If it still does not exist, it will report an error
  2. To access global variables in a function, you can use the window object
  3. There is also an early declaration feature in the function scope , and the function declaration is also executed before all the code in the function is executed.
  4. In a function, variables declared without var are called global variables , which are equivalent to the properties of the window object.
  5. A formal parameter is equivalent to declaring a variable in a function action



8. this

introduce

  1. When the parser calls a function, it will pass an implicit parameter to the function every time. This parameter is this, and this points to an object.
  2. This object we call the context object of the function execution
  3. Depending on how the function is called, this will point to different objects:
    • When called as a function, this is always window
    • When called as a method, this is the object on which the method is called



9. Prototype Objects

introduce

  1. For every function we create, the parser adds a property prototype to the function ,This property corresponds to an object, this object is what we call the prototype object .

  2. If the function is called as a normal function, the prototype has no effect

  3. When a function is called in the form of a constructor, the object it creates will have an implicit property that points to the prototype object of the constructor. We can access this property (double underscore) through **__proto__**.

  4. The prototype object is equivalent to a public area. All instances of the same class can access this prototype object. We can uniformly set the common content of the object into the prototype object.

  5. When we access an attribute or method of an object, he will first look for it in the object itself, if there is one, it will be used directly, if not, it will be searched in the prototype object of the object, and it will be used if it is found.

  6. When creating a constructor in the future, you can uniformly add the properties and methods common to these objects to the prototype object of the constructor, so that you can make each object without adding properties and methods to each object and affecting the global scope. Objects have properties and methods.

  7. A prototype object is also an object, so it also has a prototype. When we use a property or method of an object, we will first find it in itself. If not, we will look for it in the prototype object. If it still does not exist, we will look in the prototype object of the prototype until we find the prototype of the Object object.

insert image description here




10. Arrays

10.1 Four methods of arrays

  1. push() : add one or more elements to the end of the array
  2. pop() : removes the last element of the array and returns the removed element as the return value
  3. unshift() : Adds one or more elements to the beginning of the array, and returns the new array length
  4. shift() : removes the first element of the array and returns the removed element as the return value


10.2 forEach()

introduce

  1. The forEach() method requires a callback function as a parameter
  2. There are several elements in the array, and the function is executed several times . Each time it is executed, the browser will pass the traversed elements in in the form of actual parameters.
  3. The browser will pass three parameters in the callback function:
    • The first parameter is the element currently being traversed
    • The second parameter is the index of the element currently being traversed.
    • The third parameter is the array we are traversing
  4. This method only supports browsers above IE8. If you need to be compatible with IE8, do not use forEach


10.3 slice() and splice()

introduce

  1. slice() : The selected element can be returned from the array. This method will not affect the original array, but will encapsulate the intercepted elements into a new array for return, open on the left and close on the right .

    • parameter:

      • The position where the interception starts: start

      • The position where the interception ends: end

        let arr=["a","b","c","d","e"];
        console.log(arr.slice(0, 3)); //["a", "b", "c"]
        
  2. splice() : It can delete the specified element in the array, which will affect the original array, delete the specified element from the original array, and return the deleted element as the return value.

    • parameter:

      • first: the index of the starting position

      • The second: the number of deletions

      • The third and later: new elements can be passed, and these elements will be automatically inserted before the starting position index.

        <script>
            let arr=["a","b","c","d","e"];
            console.log(arr.splice(0, 3,'aaa'));
            console.log(arr);  //["aaa", "d", "e"]
        </script>
        



11. call、apply

introduce

  1. These two methods are both methods of function objects and need to be called through the function object.
  2. When calling call() and apply() on a function object, both function execution is called, which is equivalent to func()
  3. When calling call() and apply(), you can specify an object as the first parameter , and this object will become this when the function is executed.
  4. call() can pass the actual parameters in sequence after the object, and the apply() method needs to encapsulate the actual parameters into an array and pass them uniformly
<script>
    let obj={
    
    name:'obj调用'}
    let obj2={
    
    name:'obj2调用'}
    function A(a,b){
    
    
        console.log(this.name)
    }
    A.call(obj,1,2)  //obj调用
    A.apply(obj2,[1,2])  //obj2调用
</script>



12. arguments

introduce

  1. When calling a function, the browser will pass in two implicit parameters each time, one is the context object this of the function, and the other is the object arguments that encapsulate the actual parameters.
  2. arguments is an array-like object, which can also manipulate data by index and get the length
  3. When calling the function, the arguments we pass are saved in arguments
  4. arguments.length can be used to get the length of the stored arguments
  5. Even if you don't define formal parameters, you can use arguments through arguments, but it's more troublesome:
    • arguments[0]: Indicates the first argument
    • arguments[1]: Indicates the second argument
  6. Arguments has an attribute: callee , this attribute corresponds to a function object, which is the function object we are currently executing



13. Dom

Called by the document object

  1. getElementById(): Get an element node object through the id attribute
  2. getElementByTagName(): Get a set of element node objects by tag name
  3. getElementsByName(): Get a set of element node objects through the name attribute

style

  1. Modify the style of the element through JS: element.style.style name = style value

  2. In CSS naming, if there is a - connection, you need to modify the style name to camel case, remove the - and then - after the capital letter

  3. The styles read and set through the style attribute are all inline styles , so they have higher priority, so they will be displayed immediately, but if you write !important in the style, the style will have the highest priority at this time. It will cause the JS to modify the style to fail.

  4. Read style: element.style.stylename

  5. Read the style the element is currently displaying: element.currentStyle.stylename , but only IE supports it,

  6. In other browsers, you can use the **getComputedStyle()** method to get the current style of the element. This method is a window method and can be used directly. Two parameters are required:

    • The first: the element to get the style
    • The second: you can pass a pseudo element, usually null

    This method will return an object, which encapsulates the style corresponding to the current element. If the obtained style is not set, it will get a real value instead of the default value. For example, if width is not set, it will not get auto. It is a length, this method does not support IE8 and below browsers

  7. The styles obtained through currentStyle and getComputedStyle() are read-only and cannot be modified. If you want to modify them, you must pass the style attribute.




14. Event objects and bindings

introduce

  1. When the response function of the event is triggered, the browser will pass an event object event as an argument to the response function each time
  2. All information related to the current event is encapsulated in the event object, such as: the coordinates of the mouse, which button of the keyboard is pressed, the direction of the mouse wheel scrolling...
  3. In IE8, when the response function is triggered, the browser will not pass the event; in IE8 and below browsers, the event is saved as a property of the window object
  4. You can cancel event bubbling by setting the event's cancelBubbl to true
  5. The target in event represents the object that triggered the event.

event delegation

  1. The delegation of events refers to the unified binding of events to the common ancestor element of the element , so that when the event on the descendant element is triggered, it will bubble up to the ancestor element, so that the event is processed through the response function of the ancestor element.
  2. Event delegation utilizes bubbling , which can reduce the number of event bindings and improve program performance through delegation.

event binding

  1. The addEventListener() method is used to bind a response function to an element, and multiple response functions can be bound to the same event of an element at the same time , so that when the event is triggered, the response function will be executed according to the binding order of the functions .

  2. parameter:

    • The string of the event, do not on

    • The callback function, which will be called back when the event is triggered

    • Whether to trigger the event in the capture phase, a boolean value is required, generally false

      btn.addEventListener("click",function(){
              
              
          alert(1);
      },false);
      btn.addEventListener("click",function(){
              
              
          alert(2);
      },false);
      btn.addEventListener("click",function(){
              
              
          alert(3);
      },false)
      
  3. In IE8, you can also use the attachEvent() method to bind events, parameters:

    • time string, to be on
    • Callback

    It can also bind multiple handler functions for an event at the same time, the difference is that it is executed first after binding, and the execution order is opposite to that of addEventListener(), that is, pop-up 3.2.1




15. Good

location

  1. If you print the location directly, you can get the information in the address bar
  2. assign() : used to jump to other pages, the same as directly modifying the location
  3. reload() : used to reload the current page, the same as the refresh button, if you pass a true as a parameter in the method, it will force the cache to refresh the page
  4. replace() : You can replace the current page with a new page, and the page will be jumped after the call, and no history record will be generated.

Guess you like

Origin blog.csdn.net/lyyrhf/article/details/115271152