Web Collection 04 (JavaScript Cognition, Basic Grammar)

1. JavaScript overview

1. What is JavaScript

1) JS introduction

Referred to as JS, it is a browser-interpreted language, nested in HTML files and handed over to the browser for interpretation and execution. Mainly used to achieve dynamic effects of web pages, user interaction and data transmission between the front and back ends.

2) JS composition

  1. Core grammar-ECMAScript standardizes the basic grammar of JS

  2. Browser Object Model- BOM Browser Object Model, provides a series of methods for operating the browser
  3. Document Object Model-DOM
    Document Object Model, provides a series of methods for manipulating documents

2. How to use

[1] Element binding event

  • Event: Refers to the user's behavior (click, double-click, etc.) or the state of the element (the focus state of the input box, etc.)

  • Event handling: The element listens to a certain event and automatically executes the event processing function after the event occurs.

  • Commonly used events: onclick (click event)

  • Syntax: Bind the event name to the element in the form of a label attribute, and customize the event handling.

    <!--实现点击按钮在控制台输出-->
    <button onclick="console.log('Hello World');">点击</button>
    

[2] The document is embedded. Use tags to write JS code

  • grammar:
<script type="text/javascript">
  alert("网页警告框");
</script>
  • Note: The tag can be written at any position of the document, and it can be written multiple times. Once loaded into the script tag, the internal JS code will be executed immediately, so different positions will affect the final execution of the code

[3] External links

  • Create an external JS file XX.js, and use it in the HTML document
<script src="index.js"></script>
  • Note: Either embedded JS code can be implemented, or external JS file can be imported, but only one of the two can be selected.

2. Basic grammar

1. Grammar specification

[1] JS is composed of statements, statements are composed of keywords, variables, constants, operators, and methods. The semicolon can be used as a sign of the end of the statement, or can be omitted
[2] JS is strictly case-sensitive
[3] Comment syntax

 单行注释使用 //
 多行注释使用 /* */

2. JS variables and constants

1) Variable

【1】 Function: Used to store the data that can be dynamically modified during the running of the program

[2] Syntax: Use key var declaration, custom variable name

var a;		//变量声明
a = 100;	//变量赋值
var b = 200; //声明并赋值
var m,n,k;	//同时声明多个变量
var j = 10,c = 20; //同时声明并赋值多个变量

[3] Naming convention:

  • Variable names, constant names, function names, method names can be customized, can be composed of numbers, letters, underscores, and $, and it is forbidden to start with a number
  • Prohibit conflicts with keywords (var const function if else for while do break case switch return class)
  • Variable names are strictly case sensitive
  • Variable names should be as clear as possible, and multiple words should be composed of small camels, for example: "userName"

[4] Note for use:

  • If the var keyword is omitted and the variable is not assigned, direct access will report an error
  • Variables are declared with the var keyword but not assigned, and the initial value of the variable is undefined
  • The variable omits the var keyword declaration, has been assigned, and can be used normally. Affects the scope of the variable

2) Constant

【1】Function: Store data that cannot be modified once defined

[2] Syntax: must be declared and assigned at the same time

const PI = 3.14;

【3】Note:

  • Once a constant is defined, it cannot be modified, and an error will be reported if it is forced to modify
  • The naming convention is the same as that of variables. In order to distinguish variables, constant names are in all uppercase letters.

3. Data Type

1) Basic data types (simple data types)

Integer

(1) Decimal representation

var a = 100;

(2) Octal representation (prefixed with 0)

var b = 021; //结果为十进制的 17

(3) Hexadecimal representation (prefixed with 0x)

var c = 0x35;//结果为十进制的 53

Use: Integers can be expressed in different hexadecimals, and will always be output in decimal when output from the console

Decimal

(1) The decimal point means var m = 1.2345;

(2) Scientific notation

  1. string String type
    String: It is composed of one or more characters, which is represented by "" or", and each character has a corresponding Unicode code.

    var s = "100";
    var s1 = "张三";
    
  2. boolean Boolean type
    There are only two values, true and false, and Boolean and number values ​​can be converted to each other. true is 1, false is 0

    var isSave = true;
    var isChecked = false;
    
  3. undefined (value returned by the program)
    special value, undefined is displayed when the variable declaration is not assigned

    var a;
    console.log(a);//undefined
    
  4. null Empty type (actively used)
    Use null when dereferencing an object, indicating that the object is empty

2) Reference data type

Mainly refers to objects, functions, etc.

3) Detection data type

typeof variable or expression
typeof (variable or expression)

var n = "asda";
console.log(typeof n);//string
console.log(typeof(n));//string

4. Data type conversion

Different types of data need to be converted when participating in operations

1) Forced type conversion

[1] Convert string type
Method: toString()
returns the converted string

var a = 100;
a = a.toString(); //"100"
var b = true;
b = b.toString(); //"true"

[2] Convert number type

  • The Number (param)
    parameter is the variable or value to be converted to the data type, and the result of the
    conversion is returned : if the conversion is successful, the number value
    is returned. If the conversion fails, NaN, (Not a Number) is returned, as long as there are non-number characters in the data, Always fail to convert, return NaN
Demo
    Number("abc")
    typeof NaN
    Number(undefined)
    Number(null)
Demo
/*整体转number,使用Number()*/
var s1 = '123';
var s2 = '101a';
var s3 = true;
var s4 = 'true';
var s5 = null;
var s6;
console.log(Number(s1),s1)    //123 '123'
console.log(Number(s2),s2)    //NaN '101a'
console.log(Number(s3),s3)    //1 true
console.log(Number(s4),s4)    //NaN 'true'
console.log(Number(s5),s5)    //0 null
console.log(Number(s6),s6)    //NaN undefined
  • The parseInt(param)
    parameter is the data to be parsed.
    Function: Parse the integer value from the data.
    Process:
    1. If the parameter is a non-string type, it will be automatically converted to a string
    . 2. Turn each character to number from left to right. , If the conversion fails, the backward parsing is stopped and the result is returned
/*
提取字符串中的number部分:会将非字符串的数据自动转换成字符串
parseInt(n)
parseFloat(n)
*/
console.log(parseInt(35.5))            //35
console.log(parseInt("35.5"))          //35
console.log(parseFloat('35.5.6.6'))    //35.5
console.log(parseFloat('a35.5'))       //NaN
console.log(parseFloat('101a'))        //101 
  • parseFloat(param)
    function: extract number value, including integer and decimal part

2) Implicit type conversion (automatic conversion)

  1. When a character string and other data types are subjected to "+" operation, it means the splicing of character strings is no longer a mathematical operation.
    Conversion rule: After converting non-string data into character strings, splicing is performed, and the final result is a character string

  2. In other cases, always convert the operand to number for mathematical operations

Demo
var r1 = "我学"+"Python";
console.log(r1,typeof r1)  //我学Python string
var r2 = 'maple'+31;
console.log(r2,typeof r2)  //maple31 string
var r3 = 'maple'+true;
console.log(r3,typeof r3)  //mapletrue string
var r4 = 'maple'+null;
console.log(r4,typeof r4)  //maplenull string
var r5 = 'maple'+undefined;
console.log(r5,typeof r5)  //mapleundefined string
var r6 = 'maple'+NaN;
console.log(r6,typeof r6)  //mapleNaN string        
var r7 = 'maple'+5+10;
console.log(r7,typeof r7)  //maple510 string
var r8 = 10+5+'maple';  
console.log(r8,typeof r8)  //15maple string

5. Operators

1) Assignment operator

= 将右边的值赋给左边变量

2) Arithmetic operators

+ - * / %  加 减 乘 除 取余

3) Compound operator

+= -= *= /= %=

4) Increment or decrement operator

++ -- 变量的自增和自减指的是在自身基础上进行 +1或-1 的操作
Demo
var s = true;
s++;
console.log(s,typeof s)        //2 Number


var n =5;
var r =n++ + ++n + n++ + ++n +n;
        //5+   7+  7+     9+  9
//分解
var r1=n++;    //r1=5 n=6
var r2=++n;    //r2=7 n=7
var r3=n++;    //r3=7 n=8
var r4=++n;    //r4=9 n=9
var r5=+n;    //r5=9 n=9

note:

  • When the increment or decrement operator is combined with a variable alone, there is no difference between before and after
  • If the increment or decrement operator is used in combination with other operators, the prefix and the suffix must be distinguished, and the prefix must be ++/– before assignment or other operations. If the suffix is ​​used, the other operators must be combined first. Continue ++ / –

5) Relational operator/comparison operator

> <     
>= <=
==(相等) !=(不相等)
===(全等) !==(不全等)

[1] Relational operators are used to determine the relationship between expressions, and the result is always a boolean true/false

【2】Use

  • Comparison between string and string Compare
    the Unicode code of each character in turn, as long as a character compares the result, the final result is returned
  • In other cases,
    the operand is always converted to number for numerical comparison. If an operand cannot be converted to number, it becomes NaN and participates in the comparison operation, and the result is always false
null和其他数据类型做等值比较运算 不转换成数字
null和undefined相等 但是 null和undefined不全等
Demo
var res1=10>2;
var res2='10'>'2';                    //'1'>'2'
var res3 = '人生苦短'>'我学Python';     //'人'>'我';
console.log(res1,res2,res3)           //true false false
var s1 = '人';
var s2 = '我';
//获取字符的 Unicode编码charCodeAt(index)
console.log(s1.charCodeAt(),s2.charCodeAt(),res3)//20154 25105 false

var res4 = '10'>2;
var res5 = '10'>true;            //10>1
var res6 = true > false;         //1>0
console.log(res4,res5,res6)      //true true true

var res7 = '10'>undefined;       //10>NaN  false
var res8 = '10'>null;            //10>0
var res9 = 'true' > false;       //NaN>0
console.log(res7,res8,res9)      //false true false

[3] Equality and congruence

  • Equality: Regardless of data type, only value comparison (including automatic type conversion)
  • Congruence: Data type conversion will not be performed, and the data type is required to be consistent and the value is equal to judge the congruence
Demo
var r1 = 10=='10';
var r2 = 10==='10';
console.log(r1,r2);    //true false

6) Logical operators

  1. && Logic and condition 1&& condition 2 (and)
    expression is established at the same time, the final result is true; all 1 is 1
  2. || Logical OR Condition 1|| Condition 2 (or)
    As long as one of the expressions is true, the final result is true; if there is 1, then 1
Demo
//给出闰年判断的条件 能被4整除,不能被100整除,或者被400整除
var year=2015;
var r=year%4==0&&year%100!==0 ||year%400==0;
console.log(typeof year,r)        

//"number" false
  1. ! Logical negation! The condition (not)
    negates the result of an existing expression.
    Note: All values ​​except zero are true
Demo
var r1 = !5;         //false
//逻辑非的优先级高于关系运算
var r2 = !5<3;        //true  false<3
console.log(r1,r2)    //false true

7) Ternary operator

Syntax:

表达式1 ? 表达式2 : 表达式3;

Process:

	判断表达式1是否成立,返回布尔值
​	如果表达式1成立,执行表达式2;
​	如果表达式1不成立,执行表达式3;

Demo
var a = 10;
if (a>5){
    
    
    console.log('成立');    //成立
}else{
    
    
    console.log('不成立');
}
var res=a>5?'ok':'error';
console.log(res)    //ok
a = 3;
var res2 = a>5?'ok':a>=3?'>=3':'<3';
console.log(res2)    //>=3

Guess you like

Origin blog.csdn.net/weixin_38640052/article/details/107220593