Introduction to JavaScript Basics 03

Table of contents

1.Conditional statement

1.1if statement

1.1.1Basic syntax format

1.1.2 Practice cases

1.2 Ternary expression

1.3switch

2. Loop statement

2.1while loop

2.2continue

2.3break

2.4for loop

3.Array

3.1 Create array

3.2 Get array elements

3.3 Add new array elements

3.3.1. Add new by modifying length

3.3.2. Add via subscript

3.3.3. Use push to append elements

3.4 Delete elements in an array

4. Function

4.1 Grammar format

4.2 About the number of parameters

4.3 Function expression

4.4 Scope

4.5 Scope chain

5.Object

5.1Basic concepts

5.2. Use literals to create objects [Commonly used]

5.3. Create objects using new Object

5.4. Create objects using constructors

5.5 Understanding the new keyword


1.Conditional statement

1.1if statement

1.1.1Basic syntax format

If the conditional expression is true, the code in { } of if is executed.

// 形式1
if (条件) {
  语句
}
// 形式2
if (条件) {
  语句1
} else {
  语句2
}
// 形式3
if (条件1) {
  语句1
} else if (条件2) {
  语句2 
} else if .... {
  语句...
} else {
  语句N
} 

1.1.2 Practice cases

Code example 1: Determine whether a number is odd or even

var num = 10;
if (num % 2 == 0) {
  console.log("num 是偶数");
} else {
  console.log("num 是奇数");
}

Note! You cannot write num % 2 == 1 as it is an odd number. A negative odd number % 2 may result in -1.

Code example 2: Determine whether a number is positive or negative

var num = 10;
if (num > 0) {
  console.log("num 是正数");
} else if (num < 0) {
  console.log("num 是负数");
} else {
  console.log("num 是 0");
}

Code example 3: Determine whether a certain year is a leap year

if (year % 100 == 0) {
  // 判定世纪闰年
  if (year % 400 == 0) {
    console.log("是闰年");
 } else {
    console.log("不是闰年");
 }
} else {
  // 普通闰年
  if (year % 4 == 0) {
    console.log("是闰年");
 } else {
    console.log("不是闰年");
 }
}

1.2 Ternary expression

It is a simplified way of writing if else.

条件 ? 表达式1 : 表达式2

If the condition is true, return the value of expression 1. If the condition is false, return the value of expression 2.
Note that the priority of ternary expressions is relatively low.

1.3switch

More suitable for multi-branch scenarios.

switch (表达式) {
  case 值1:
    语句1;
    break;
  case 值2:
    语句2:
    break;
  default:
    语句N;
}

The user enters an integer to prompt what day of the week today is.

var day = prompt("请输入今天星期几: ");
switch (parseInt(day)) {
  case 1:
    console.log("星期一");
    break;
  case 2:
    console.log("星期二");
    break;
  case 3:
    console.log("星期三");
    break;
  case 4:
    console.log("星期四");
    break;
  case 5:
    console.log("星期五");
    break;
  case 6:
    console.log("星期六");
    break;
  case 7:
    console.log("星期日");
    break;
  default:
    console.log("输入有误");
}

2. Loop statement

Repeat certain statements

2.1while loop

while (条件) {
  循环体;
}

Execution process:
        Execute the conditional statement first
        If the condition is true, execute the loop body code.
        The condition is false, end the loop directly

Code example 1: Print 1 - 10

var num = 1;
while (num <= 10) {
  console.log(num);
  num++;
}

Code Example 2: Calculate the factorial of 5

var result = 1;
var i = 1;
while (i <= 5) {
  result *= i;
  i++;
}
console.log(result)

2.2continue

End this cycle
After eating five plums, I found a bug in the third plum, so I threw it away and continued to eat the next plum.

var i = 1;
while (i <= 5) {
  if (i == 3) {
    i++;
    continue;
 }
  console.log("我在吃第" + i + "个李子");
  i++;
}
我在吃第1个李子
我在吃第2个李子
我在吃第4个李子
我在吃第5个李子

Code example: Find all multiples of 3 in 100 - 200

var num = 100;
while (num <= 200) {
  if (num % 3 != 0) {
    num++;  // 这里的 ++ 不要忘记! 否则会死循环.
    continue;
 }
  console.log("找到了 3 的倍数, 为:" + num);
  num++;
}

2.3break

End the whole cycle
After eating five plums, I found that there was half a worm in the third plum, so I didn’t eat the rest.

var i = 1;
while (i <= 5) {
  if (i == 3) {
    break;
 }
  console.log("我在吃第" + i + "个李子");
  i++;
}
我在吃第1个李子
我在吃第2个李子

Code example: Find the first multiple of 3 in 100 - 200

var num = 100;
while (num <= 200) {
  if (num % 3 == 0) {
    console.log("找到了 3 的倍数, 为:" + num);
    break;
 }
  num++;
}
// 执行结果
找到了 3 的倍数, 为:102

2.4for loop

for (表达式1; 表达式2; 表达式3) {
循环体
}

Expression 1: used to initialize loop variables.
Expression 2: loop condition
Expression 3: update loop variables.         Then execute expression 2, determine loop conditions         First execute expression 1, initialize loop variables
Execution process:         If the condition is true, execute the loop body code.         Execute expression 3 and update the loop variable




Code example 1: Print numbers 1 - 10

for (var num = 1; num <= 10; num++) {
  console.log(num);
}

Code Example 2: Calculate the factorial of 5

var result = 0;
for (var i = 1; i <= 5; i++) {
  result *= i;
}
console.log("result = " + result);

3.Array

3.1 Create array

Created using the new keyword

// Array 的 A 要大写
var arr = new Array();

Create using literal method [Commonly used]

var arr = [];
var arr2 = [1, 2, 'haha', false]; // 数组中保存的内容称为 "元素"

Note: JS arrays do not require the elements to be of the same type.
This is very different from statically typed languages ​​such as C, C++, and Java. But dynamically typed languages ​​such as Python and PHP The same goes for language.

3.2 Get array elements

Access array elements using subscripts (starting from 0)

var arr = ['小猪佩奇', '小猪乔治', '小羊苏西'];
console.log(arr);
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
arr[2] = '小猫凯迪';
console.log(arr);

If the subscript is out of range to read the element, the result is undefined

console.log(arr[3]);  // undefined
console.log(arr[-1]);  // undefined

Note: Do not assign a value directly to the array name, otherwise all elements in the array will be lost.

It is equivalent to arr being an array originally, but it becomes a string after reassignment.

var arr = ['小猪佩奇', '小猪乔治', '小羊苏西'];
arr = '小猫凯迪';

3.3 Add new array elements

3.3.1. Add new by modifying length

Equivalent to adding a new element at the end. The default value of the new element is undefined

var arr = [9, 5, 2, 7];
arr.length = 6;
console.log(arr);
console.log(arr[4], arr[5]);

3.3.2. Add via subscript

If the subscript exceeds the range of the assigned element, a new element will be inserted at the specified position.

var arr = [];
arr[2] = 10;
console.log(arr)

At this time, [0] and [1] of this array are both undefined

3.3.3. Use push to append elements

Code example: Given an array, put the odd numbers in the array into a newArr.

var arr = [9, 5, 2, 7, 3, 6, 8];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
  if (arr[i] % 2 != 0) {
    newArr.push(arr[i]);
 }
}
console.log(newArr);

3.4 Delete elements in an array

Remove elements using splice method

var arr = [9, 5, 2, 7];
// 第一个参数表示从下表为 2 的位置开始删除. 第二个参数表示要删除的元素个数是 1 个
arr.splice(2, 1);
console.log(arr);
// 结果
[9, 5, 7]

At present, we have used some properties and methods in the array.
arr.length, length is used without parentheses. At this time, length is an ordinary variable (called Member variables, also called attributes) arr.push(), arr.splice() are used with parentheses, and parameters can be passed. At this time Is a function (also called a method)

4. Function

4.1 Grammar format

// 创建函数/函数声明/函数定义
function 函数名(形参列表) {
  函数体
  return 返回值;
}
// 函数调用
函数名(实参列表)      // 不考虑返回值
返回值 = 函数名(实参列表)  // 考虑返回值

The function definition does not execute the function body content, it must be called before it is executed. It will be executed several times after it is called several times.

function hello() {
  console.log("hello");
}
// 如果不调用函数, 则没有执行打印语句
hello();

When calling a function, it enters the internal execution of the function. When the function ends, it returns to the calling location to continue execution. You can use the debugger to observe.
There is no requirement for the order of function definition and calling. . (This is different from variables, which must be defined first and then used)

// 调用函数
hello();
// 定义函数
function hello() {
  console.log("hello");
}

4.2 About the number of parameters

The number of actual parameters and formal parameters does not need to match. However, actual development generally requires that the number of formal parameters and actual parameters must match
1) If the number of actual parameters is greater than If there are too many formal parameters, the extra parameters will not participate in the function operation

sum(10, 20, 30);   // 30

2) If the number of actual parameters is less than the number of formal parameters, the value of the extra formal parameters will be undefined.

sum(10);   // NaN, 相当于 num2 为 undefined.

JS's function parameter passing is relatively flexible, which is quite different from other languages. In fact, this flexibility is often not a good thing.

4.3 Function expression

Another way to define a function

var add = function() {
var sum = 0;
  for (var i = 0; i < arguments.length; i++) {
    sum += arguments[i];
 }
  return sum;
}
console.log(add(10, 20));       // 30
console.log(add(1, 2, 3, 4));     // 10
console.log(typeof add);       // function

At this time, an anonymous function is defined in the form of function() { }, and then the anonymous function is represented by a variable.
You can later use this add variable It’s time to call the function.
Functions in JS are first-class citizens. They can be saved in variables, and can also be used as parameters or return values ​​of other functions.

4.4 Scope

The valid scope of an identifier name in the code.
Before the ES6 standard, the scope was mainly divided into two types
Global scope: It takes effect in the entire script tag, or in a separate js file.
Local scope/function scope: takes effect inside the function.

// 全局变量
var num = 10;
console.log(num);
function test() {
  // 局部变量
  var num = 20;
  console.log(num);
}
function test2() {
  // 局部变量
  var num = 30;
  console.log(num);
}
test();
test2();
console.log(num);
// 执行结果
10
20
30
10

If you do not write var when creating a variable, you will get a global variable.

function test() {
num = 100;
}
test();
console.log(num);
// 执行结果
100

In addition, the scope of local variables in many languages ​​is divided according to code blocks (braces), which was not the case in JS before ES6.

if (1 < 2) {
var a = 10;
}
console.log(a);

4.5 Scope chain

Background:
Functions can be defined inside functions
Inner functions can access local variables of outer functions.
The internal function can access the variables of the external function. A chain search is adopted. The search is performed from the inside to the outside.

var num = 1;
function test1() {
  var num = 10;
  function test2() {
    var num = 20;
    console.log(num);
 }
  test2();
}
test1();
// 执行结果
20

When console.log(num) is executed, num will be searched in the local scope of test2. If it is not found, it will continue to search in test1. If it has not been found, it will search in the global scope.

5.Object

5.1Basic concepts

An object refers to a specific thing.
        "Computer" is not an object, but a general category. And "My Lenovo Notebook" is an object .
In JS, strings, values, arrays, and functions are all objects.
Each object contains several properties and methods.
        Attributes: Characteristics of things.
        Methods: Behaviors of things.
        For example, you have a girl.
        Her height, weight, and body measurements are all attributes.
        Her singing, dancing, and bed-warming are all methods.

5.2. Use literals to create objects [Commonly used]

Create objects using { }

var a = {};  // 创建了一个空的对象
var student = {
  name: '蔡徐坤',
  height: 175,
  weight: 170,
  sayHello: function() {
    console.log("hello");
 }
};

Use { } to create objects
Properties and methods are organized in the form of key-value pairs.
Key-value pairs are divided using, split. Finally Behind an attribute, it is optional
Use: split between key and value.
The value of the method is an anonymous function

Using object properties and methods:

// 1. 使用 . 成员访问运算符来访问属性 `.` 可以理解成 "的"
console.log(student.name);
// 2. 使用 [ ] 访问属性, 此时属性需要加上引号
console.log(student['height']);
// 3. 调用方法, 别忘记加上 ()
student.sayHello();

5.3. Create objects using new Object

var student = new Object(); // 和创建数组类似
student.name = "蔡徐坤";
student.height = 175;
student['weight'] = 170;
student.sayHello = function () {
  console.log("hello");
}
console.log(student.name);
console.log(student['weight']);
student.sayHello();

Note that objects created using { } can also use student.name = "Cai Xukun" to add attributes at any time.

5.4. Create objects using constructors

The previous object creation method can only create one object. Using the constructor can easily create multiple objects.
For example: Create several cat objects

var mimi = {
  name: "咪咪",
  type: "中华田园喵",
  miao: function () {
    console.log("喵");
 }
};
var xiaohei = {
  name: "小黑",
  type: "波斯喵",
  miao: function () {
    console.log("猫呜");
 }
}
var ciqiu = {
  name: "刺球",
  type: "金渐层",
  miao: function () {
    console.log("咕噜噜");
 }
}

It is more troublesome to write at this time. Using constructors can extract the creation of the same properties and methods, simplifying the development process.

basic grammar

function 构造函数名(形参) {
  this.属性 = 值;
  this.方法 = function...
}
 
var obj = new 构造函数名(实参);

Note:
        Use the this keyword inside the constructor to indicate the object currently being constructed.
        The first letter of the function name of the constructor is generally Uppercase.
        The function name of the constructor can be a noun.
        The constructor does not need to return
        It must be used when creating an object new keyword.

Use the constructor to recreate the cat object

function Cat(name, type, sound) {
  this.name = name;
  this.type = type;
  this.miao = function () {
    console.log(sound); // 别忘了作用域的链式访问规则
 }
}
var mimi = new Cat('咪咪', '中华田园喵', '喵');
var xiaohei = new Cat('小黑', '波斯喵', '猫呜');
var ciqiu = new Cat('刺球', '金渐层', '咕噜噜');
console.log(mimi);
mimi.miao();

5.5 Understanding the new keyword

new execution process:
1. First create an empty object in memory { }
2. this points to the empty object just now ( Use the object in the previous step as the context of this)
3. Execute the code of the constructor and create properties and methods for the object
4. Return the object (constructor There is no need for return, new does it for you

Guess you like

Origin blog.csdn.net/qq_65307907/article/details/133758592