The latest and most complete JavaScript introductory video, including JavaScript knowledge learning related to applets and uniapp

written in front

We learn JavaScript not only for web site development, but also for the development of small programs and uniapp projects, so it is very important for us to learn JavaScript.

Preparation

We use the applet developer tool or uniapp developer tool to learn JavaScript here, so you need to install one of these two first.

Of course, if you want to learn small programs while learning js, Shitou recommends using the small program developer tools.
If you just learn uniapp and don’t want to learn small programs, just download the uniapp developer tools.

Download the corresponding developer tools according to your own needs. If you can’t enter the above two points, you can go to Shitou’s personal blog to find articles corresponding to getting started with small programs or getting started with uniapp.

1. Learning of functions and events

1-1, the learning of annotations

Before we study the following courses, let's learn about annotations. Comments are used to give hints in the code, mainly to let others get familiar with your code faster, and it is also convenient for you to look at your own code later and recall it quickly.
— Comments with shortcut keys —

  • Windows computer: Ctrl+/
  • Mac computer: command+/

1-1-1, Notes in Mini Programs

The comments in wxml are as follows

Comments in wxss Comments

in js

1-1-2, Notes in uniapp

Before we study the following courses, let's learn about annotations. Comments are used to give hints in the code, mainly to let others get familiar with your code faster, and it is also convenient for you to look at your own code later and recall it quickly. Note that there are shortcut keys, just as we have mentioned commonly used shortcut keys in the previous section.

  • Windows computer: Ctrl+/
  • Mac computer: command+/

You can see that the three commonly used annotations are as follows, which correspond to the Three Musketeers we learned earlier.

  • The annotations for the layout are:<!-- -->
  • The comment of the js logic code is: //
  • The css-style comments are: /* */

    We don’t need to memorize the writing of each comment here, we only need to remember the shortcut keys to quickly generate comments. This is the benefit of shortcut keys.

1-2, the learning of log printing

1-2-1, log printing in the applet

Before we learn click events, we need to learn log printing, because log printing is often used in our development process. The syntax of log printing is as follows

console.log("我的打印出来的日志内容")

1-2-2, log printing in uniapp

1-3, function learning

The two ways of using the function are as shown in the figure below:

The definition of the function is the same in the applet as in uniapp.
The two ways of using the function are as shown in the figure below:

Our functions are generally written in the methods of the js logic area. For example, if we define a getname function, there are the following two ways of writing.

Brother Stone here recommends the first way to define functions, which is also simpler

1-4, click event learning

1-4-1, the click event in the applet

If we want to define a click event for a component, we need to use bindtap. The syntax for binding a click event to a component is as follows.

We define a click event for a component, mainly by defining a bindtap="event name" for the component, and then define the same function as the event name in the js page. It will be explained in detail in the video

1-4-2, click event in uniapp

Next, we learn about events. Our commonly used events are as follows. Here we will focus on @click click events and
@input events to obtain input values.

If we want to define a click event for a component, we need to use uni's event processing. Since uni is based on the vue syntax, we need to use vue's syntax to define click events for components in uni.
The syntax for binding a click event to a component is as follows:

We can use the v-on directive to listen for click events to execute JavaScript code.
The v-on directive can be abbreviated with the @ sign.

Grammar format:

v-on:click="methodName"
@click="methodName"

methodName is the function name, as shown below,

we can see that we can define click events by using both v-on and @, and I recommend you to use @ abbreviation here

1-5, get user input information

1-5-1, Obtain user input in the applet

We will use the bindinput event to obtain user input. In fact, when we are learning the input component, the official has given this attribute. https://developers.weixin.qq.com/miniprogram/dev/component/input.html

Look at the official documentation, you can know that bindinput is mainly to obtain user input.
The definition of bindinput is as shown below.

After defining the bindinput event in wxml, define a function with the same name as the event on the js page. The video will explain in detail. If you have bought the teacher's course, or purchased the teacher's annual card, you can get the corresponding learning video.

1-5-2, get user input in uniapp

There are two ways to get the content entered by the user in the input input box in uniapp

  • @input binding function
  • v-model data binding to get input content (recommended)

We will use the @input event to obtain user input. In fact, when we are learning the input component, the official has given this property.

Looking at the official documentation, you can know that @input is mainly to obtain user input.
The definition of @input is as shown in the figure below, where getname is the function we defined to receive user input.

After defining the bindinput event in the layout, define a function with the same name as the event on the js page.

Then you can monitor the user input, which

will be explained in detail in the video. If you have bought the teacher's course, or purchased the teacher's annual card, you can get the corresponding learning video.

Second, variable learning

2-1, what is a variable

In the vernacular: a variable is a box for holding things.
In layman's terms: a variable is a container for storing data, and we obtain the corresponding data through the variable name.

As shown in the figure above, our box (variable) can hold names, boolean true, and numbers.
The essence of variables: it is to apply for a space in the program's memory to store data.

2-2, Composition of variables

A variable consists of a variable name and a stored value, the syntax is as follows

var x = 7;
var y = 8;
var z = x + y; 

从上例中,您可知道x,y,z是三个不同的变量名:
x 存储值 7
y 存储值 8
z 存储值 15

Variables are a bit like our hotel rooms. A room can be considered a variable. For example, our room 808 is a couple room. Then the room number 808 is equivalent to our variable name, and the couple room is the value stored in this variable.

2-3, the use of variables

Variables are used in two steps:

  • 1. Declare variables

Look at the specific code

//声明变量
var age 

The meaning of this code is to declare a variable called age
var is a JavaScript keyword used to declare a variable. After using this keyword to declare a variable, the computer will automatically allocate a memory space for the variable to store data.
age is our variable name, we need to use the variable name to access the space allocated in the computer memory.

  • 2. Assignment

Or take our hotel room as an example, declaring variables is equivalent to checking in at the front desk, determining which room to live in, that is, determining the room number (variable name), and then determining the room type corresponding to the room number, such as single room, double room, Lovers room. Determining the room type is equivalent to assigning values ​​to variables.

//给age赋值
age=10

The meaning of this code is to assign the age variable a value of 10.
The above = is used to assign the value on the right to the variable name on the left, that is, point our variable name age to the value 10, and then we can use age to manipulate our value. up. The purpose of assignment is to use the value later.

2-4, variable initialization

The use of our variables above can be written directly to one line

var age=10 

Declaring a variable and assigning a value to the variable at the same time, we call it the initialization of the variable.

2-5, variable reassignment

A variable can be reassigned, and the new assignment will overwrite the previous assignment, and the variable value will be based on the last assigned value.

var age=10
age=18

As in the above code, our variable age is first assigned a value of 10, and then assigned a value of 18, then our age is 18 in the end. This is
like the hotel room, room 808, where Brother Shitou first lived, and Brother Shitou left later. , Andy Lau has moved in, then at this time you go to 808 to find someone, and the one you find is Andy Lau.

2-6. Variable naming convention

  • Names can contain letters, numbers, underscores, and dollar signs
  • Name must start with a letter
  • Names are case sensitive (y and Y are different variables)
  • Cannot be keywords, reserved words (such as JavaScript keywords)
  • Follow the camel case naming convention, the first letter is lowercase, and the first letter of the following word is capitalized. such as userName

2-7, a small case of variables

Remember how we learned how to get the information entered by the user in Section 6-5? Can we use variables to store the user input information we get?

A detailed explanation will be given in the explanation video: "Zero-Basic Introductory Small Program Development"

2-8, global variables and local variables

Local Variables: Variables are declared within a function and can only be accessed inside the function.
Global variable: A variable defined outside a function that can be called by the entire code.

The definition of local variables and global variables as shown in the figure above.

Three, data type

3-1, know the data type

In the study of variables in the previous section, we know that variables are boxes used to hold data, but there are many types of data. Different types of data occupy different calculator memory. Just like a fat person sleeps in a big bed, and a thin person sleeps in a small bed.
In the computer, different data occupy different storage spaces. In order to facilitate the distinction and make full use of the storage space, different data types are defined.
Simply put, the data type is the category model of the data. For example, "Zhang San" is a personal name, and 18 is a number.

3-2, common data types

Our data types can be divided into the following two categories

  • Simple Data Types (Number String Boolean Undefined Null)
  • complex data type (Object)

simple data type

simple data type describe Defaults
Number Numeric type, including integers and decimals, such as 18, 18.8 0
String String type, such as "little stone". Note that strings in js must be quoted “”
Boolean Boolean value type, just two values ​​of true and false, representing correct and incorrect false
Undefined Undefined This value means that the variable does not contain a value, such as var a; variable a is declared, but no value is assigned, it is undefined undefined
Null Null value, such as var a=null, declares variable a to be null null

3-3, digital Number

The data of js number type can be either an integer or a decimal (floating point number)

var age=21	//整数
var PI=3.1415	//小数

3-4, String String

Those wrapped in quotation marks or double quotation marks are all string types, such as "programming small stone", and 'Brother Stone' are all string types. Strings are a bit like kebabs, kebabs are strings of mutton skewered on bamboo sticks. Strings are just strings together.

var name="编程小石头"	//字符串
var age1="18"		//字符串
var age2=18		//数字型

There is a difference between age1 and age2 in the above code. The 18 of age1 is wrapped in double quotes, so it is a string, and age2 is a number 18, so it is a number. This further shows that as long as it is wrapped in single quotes or double quotes, it is a string type.

string length

A string is composed of several characters, the number of these characters is the length of the string, and the length of the entire string can be obtained through the length property of the string.
Still take the lamb skewers as an analogy. For example, if you skewer 5 pieces of lamb, then the length of the lamb skewers is 5.
The syntax used is as follows

    var name="编程小石头"
    console.log(name.length)	//这里的输出结果是5

concatenation of strings

Multiple strings can be spliced ​​using +, and the splicing method is string + string = new string after splicing.
The syntax is as follows:

    var name="编程小石头"
    var weixin=2501902696
    var test=name+weixin
    console.log(test) //输出结果:"编程小石头2501902696"
    console.log(12+12)//输出结果:24
    console.log("12"+12)//输出结果:1212

The above 12+12=24, "12"+12="1212" This tells us that any type of data is added to the string, and the result after splicing is a string.

3-5, Boolean Boolean

The Boolean type has two values: true and false, where true means true and false means false.

var flag=true

3-6, Undefined and Null

A variable that is not assigned a value after declaration will have a default value of undefined
. A declared variable and assigned a value of null means that the variable is a null value (when learning the object object, we will continue to study null)
null and undefined have equal values, but different types , the following 8-7 will have a code demonstration

3-7, typeof operator

The typeof operator is used to detect the data type of a variable

typeof "John"                // 返回 string 
typeof 3.14                  // 返回 number
typeof false                 // 返回 boolean

The data types of printing null and undefined are as follows

    var aaa=undefined
    var bbb=null
    console.log(aaa==bbb)//输出结果:true
    console.log(typeof aaa)//输出结果:undefined
    console.log(typeof bbb)//输出结果:object

Note: == here is used to judge whether the values ​​are equal, which will be discussed later.
It can be seen from the above code that the values ​​of null and undefined are equal, but the types are different

3-8, data type conversion

It is to convert a variable of one data type into another data type, such as converting "18" of a string to 18 of a digital type. Commonly
used data type conversion

  • Convert other types to string
  • Convert other types to numeric

convert to string

Way illustrate the case
toString() convert to string var num=1 num.toString()
String() convert to string var num=1 String(num)
Concatenate strings with plus signs convert to string var num=1 “”+num

Convert to numeric type (emphasis)

Way illustrate the case
Number() convert string to number Number("3.14") // returns 3.14
pressFloat() Parses a string and returns a float parseFloat("3.12") //return 3.12
parseInt() parses a string and returns an integer parseInt("3.12") //return 3

Several special cases of converting to numbers

console.log(Number(""))//空字符串转换为 0
console.log(Number(true))//true转换为1
console.log(Number(false))//false转换为0
console.log(Number("编程小石头"))//其他的字符串会转换为 NaN (不是个数字)

Four, comprehensive small case ~ develop a simple calculator

Here we take a small program as an example to write a small case. In fact, the principle in uniapp is the same. You can go to Shitou uniapp's notes to see: https://blog.csdn.net/qiushi_1990/article/details/127675537

4-1, data binding

Before learning this comprehensive case, we need to learn the dynamic data binding of the applet first. The syntax for data binding is as follows

<!--wxml-->
<view> {
   
   {message}} </view>

// js里如下
Page({
  data: {
    message: '我是动态绑定的数据'
  }
})

4-2, Effect picture preview

In the previous section, I explained some common components of the applet to you. This section will take you to write your first simple calculator. Do a comprehensive exercise. Since it is an introduction, here is a simple addition operation. The effect diagram is as follows. 1.png
It is very simple to implement, and the code is very small, just the following three

  • index.wxml: the layout view page of the above figure
  • index.js: A page that implements addition logic
  • app.json: Some global configurations. Basically, it’s the default and don’t worry about it here
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-n1U75mfw-1597396869759)(https://upload-images.jianshu. io/upload_images/6273713-2b8639cf9f1fc8ea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)] The
    following will take you to type out your own calculator applet code.

4-3, first look at index.wxml

<!--index.wxml  -->
<input placeholder="请输入数字a" bindinput="inputa" />
<text>+</text>
<input placeholder="请输入数字b" bindinput="inputb" />
<button bindtap='sum'>计算</button>
<text>结果为:{
   
   {result}}</text>

Although there are few codes, as a beginner, you may seem at a loss. Let me tell you in detail below.

<input placeholder="请输入数字a" bindinput="inputa" /> 
<input placeholder="请输入数字b" bindinput="inputb" />

It is the input box where we enter the number a, where input is the first applet component we know.
The official introduction of input is as follows: https://developers.weixin.qq.com/miniprogram/dev/component/input.html
placeholder: set the default display text (when we input text, the default will be gone)
bindinput="inputa ": Define an inputa method to get the input content of input. Will be used in index.js

  • +
    here Components are used to display text here we just want to display a + sign
<button bindtap='sum'>计算</button>

Here is a button that is our calculation button
bindtap='sum': define a method called sum, which is used to calculate the result and will be used in index.js

  • The result is: { {result}}
    { {result}} This writing method is used by applets to bind data, and here it is used to display our calculation results.

The above code and the corresponding display are as follows:

4.jpg

4-4, let’s look at index.js again, the logical realization of our addition

You can see that the bindinput="inputa" and bindtap='sum' we defined in index.wxml are useful below

Page({
  /**
     * 页面的初始数据
     * 初始化两个输入值
     */
  data: {
    input1: 0,
    input2: 0
  },
  //获取用户输入的值a
  inputa: function (e) {
    this.setData({
      input1: e.detail.value
    })
  },
  //获取用户输入的值b
  inputb: function (e) {
    this.setData({
      input2: e.detail.value
    })
  },
  // 拿到两个输入值以后求和
  sum: function (e) {
    var a = parseInt(this.data.input1);
    var b = parseInt(this.data.input2);
    // 求和
    var sumResult = a + b
    this.setData({
      // 把结果赋值到sum标签上
      result: sumResult
    })
  }
})

There are not many codes in index.js, so you can follow them first. You don't need to understand the early stage of learning small programs, but you must practice more and more.
The logic here is written in words. It is estimated that it is not easy for everyone to understand when they are new. I will record a video to explain it to you.

4-5, homework, write a subtraction calculator by yourself

Five, the operator

Operators, also known as operators, are symbols used to implement functions such as assignment, comparison, and operation.

5-1, arithmetic operators

operator describe example x operation result
  • |addition| x=5+2 |7
  • |subtraction| x=5-2 |3
  • |multiplication|x=5*2| 10
    / |division| x=5/2 |2.5
    %|modulo (remainder)| x=5%2| 1

5-2, expressions and return values

Expression: It is a formula composed of numbers, operators, variables, etc., and meaningful operations that can obtain results.
The expression will eventually have a result returned to us, which we call the return value

  • For example, let x=1+1
    where 1+1 is an expression composed of numbers and plus signs, and then the result 2 will be returned and assigned to x, then the value of x is 2. In layman's terms, it is to first calculate the expression on the right and then return the value to x on the left.

5-3, comparison operators

The comparison operator is the operator used when comparing two data. After the comparison operation, it will return a Boolean result, which is to return true or false (true or false)

operator describe the case result
< Less than sign 1<2 true

|Greater than |1>2|false
=|Greater than or equal to (greater than or equal to)|1>=2|false
<=|Less than or equal to (less than or equal to)|1<=2|true
|Equality sign (judging whether it is equal)|11|true
=|absolutely equal (both value and type are equal)|1='1'|false
!=|not equal to |1!=1|false

5-4, assignment operator

Assignment operators assign values ​​to JavaScript variables.

operator example Equivalent to
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

= summary

  • =: assignment, assign the right side to the left such as a=b
  • ==: Judgment, judge whether the values ​​on both sides are equal, such as a ==b
  • === : Congruent, judge whether the values ​​and data types on both sides are completely equal, such as a === b

5-5, logical operators

It is used to judge multiple conditions, and its return value is a Boolean value.

  • && Logical AND, both conditions must be met, and the result is true only if both sides are true
  • || Logical or, only one of the two conditions needs to be satisfied, and the result is true if one side is true
  • ! Logical not not, logical negation, such as the opposite value of true is false

For example, if you want to recharge your phone bill

  • && You want to use WeChat to charge: You must have WeChat and use WeChat to pay for charging
  • || You go to the business hall to recharge: WeChat or Alipay can be paid
  • ! If there are only two ways: Alipay and WeChat: If you don’t want to use WeChat, you can only use Alipay

5-6, increment and decrement operators

Overview of Increment and Decrement Operators: If you need to repeatedly add or subtract 1 to a numeric variable, you can use the increment (++) and decrement (–) operators to do so.
In js, increment (++) and decrement (–) can be placed in front of the variable or after the variable. When placed in front, it is called pre-increment or decrement operator, and when it is placed in the back, it is called post-increment or decrement operator.
Note: Increment or decrement can only operate variables, and cannot directly operate numbers.

5-6-1, Pre-increment decrement operator

Note: When pre-incrementing or decrementing, it is first incremented or decremented, and then returns the value.
We wanted to add 1 to a variable before and write it as follows

var num=1
num=num+1 //这里就是给num加1

Do we have a convenient way to write it? The above num=num+1 can be directly written as ++num. Is this more concise?

5-6-2, post increment decrement operator

Note: When post-incrementing or decrementing, the value is returned first, and then incremented or decremented

5-6-3, the difference between front and rear

  • The effect is the same if the front and rear are used alone
  • The preposition is to add or decrement first, and then return the value; the postposition returns the value first, and then adds or decrements
var num=10
console.log(++num  +10)//结果是21
console.log(num++  +10)//结果是20

Let's strengthen our understanding through the following small examples

var a=10
++a
console.log(b)//这里b的结果是几

var c=10
c++
var d=c++ +2
console.log(d)//这里d的结果是几

var e=10
var f=e++ + ++e
console.log(f)//这里f的结果是几

5-6-4, summary of pre- and post-incrementing and decrementing

  • The main purpose of pre and post is to simplify code writing
  • When using increment or decrement alone, the pre and post effects are the same
  • When used in conjunction with other operations, the execution results will be different.
    Post: return the original value first, and then add it (self first)
    Pre: add itself first, then return the value (self first)
    can be summarized as: selfish , followed by disinterested
  • When developing, post-increment/decrement is mostly used. For example num++ or num- -

Six, conditional statements and loop statements

6-1, process control

Before learning conditional statements and loop statements, we need to know what flow control is,
**flow control: **flow control is to control the order in which our code is executed.
There are three main structures of process control

  • sequential structure
  • branch structure
  • Loop structure

    The sequence structure is the simplest and most basic flow control in the program, that is, the codes are executed sequentially. We focus on explaining branching structures and looping structures.

6-2, branch structure

The branch structure we mentioned above means that during the execution of the code from top to bottom, different codes are executed according to different conditions, so as to obtain different results. The statement commonly used in the branch structure is the conditional statement.
The statement of the branch structure we commonly use:

  • if statement
  • switch statement

Conditional Statements: Used to perform different actions based on different conditions, usually when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
insert image description here
To give the simplest example: you can go to Internet cafes when you are over 18 years old, and you are not allowed to enter Internet cafes if you are under 18 years old. The criterion here is your age.
What we commonly use here is the if conditional statement, so next we will focus on explaining the if conditional statement.

6-3, if conditional statement

In JavaScript, we can use the following conditional statements:

  • if statement - use this statement to execute code only if a specified condition is true
  • if...else statement - executes code when the condition is true, and executes other code when the condition is false
  • if…else if…else statement - use this statement to select one of several blocks of code to execute

6-3-1, if statement

Use an if statement to specify a block of JavaScript code to be executed if a condition is true.

  • grammar
if (条件) {
    如果条件为 true 时执行的代码
} 
  • example
if (age< 18) {
   console.log("未成年")
}

If the age is less than 18 years old, export minors

6-3-2, if else double branch statement

Use the else statement to specify a block of code if the condition is false.

if (条件) {
    条件为 true 时执行的代码块
} else { 
    条件为 false 时执行的代码块
}
  • example
if (age < 18) {
     console.log("未成年")
 } else {
    console.log("成年")
 } 

If the age is less than 18, output minor, otherwise output adult

6-3-3, if else if multi-branch statement

Use else if to specify a new condition when the first condition is false.

语法
if (条件 1) {
    条件 1 为 true 时执行的代码块
} else if (条件 2) {
    条件 1 为 false 而条件 2 为 true 时执行的代码块
 } else {
    条件 1 和条件 2 同时为 false 时执行的代码块
}
  • example
if (age < 18) {
     console.log("未成年")
 } else if(age<60) {
    console.log("成年")
 } else {
    console.log("老年")
 } 

If the age is less than 18 years old, the output is underage, the age is greater than 18 and less than 60 years old, the output is adult, and the age is greater than 60 years old, the output is old.

6-4 wxml conditional rendering

In wxml, use wx:if="" to determine whether the code block needs to be rendered:

<view wx:if="{
   
   {condition}}"> 我是可以显示的</view>

You can also use wx:elif and wx:else to add an else block:

<view wx:if="{
   
   {length > 5}}"> 1 </view>
<view wx:elif="{
   
   {length > 2}}"> 2 </view>
<view wx:else> 3 </view>

It can be seen that the conditional rendering in wxml is similar to the if conditional statement we mentioned above, but the writing is slightly different.
Conditional rendering in wxml is mainly used for page display and hiding.

6-5, for loop statement

Using a loop is handy if you want to run the same code over and over, with different values ​​each time.
For example, we want to output 5 programming small stones

  • General writing:
    console.log("programming stone") console.log("programming stone
    ") console.log("programming stone")
    console.log("programming stone") console.log("programming
    stone")
    Stone")
  • use for loop
for (var i=0;i<5;i++){ 
  console.log("编程小石头")
}

Syntax for for loop:

for (初始化变量; 条件表达式; 操作表达式){
    被执行的代码块
}
  • Initialize variable: the first execution before the start, usually used to initialize the counter variable, only executed once.
  • Conditional expression: It is used to determine whether each loop can continue to execute, and defines the termination condition of the running loop
  • Operational expressions: Executed after the block of code enclosed in curly braces has been executed, usually used to increment or decrement our counter variable.

example

for (var i=0;i<5;i++){ 
  console.log("编程小石头")
}

In the above example,
statement 1: var i=0 is to initialize the variable i before starting execution
Statement 2: i<5 is used to judge whether i is less than 5, if it is less than 5, continue to execute the loop
statement 3: i++ is to execute in each loop Add 1 to i after one pass

6-6, wxml list rendering

In wxml we use wx:for to display list data.
Bind an array with the wx:for control attribute on a component, and the component can be rendered repeatedly with the data of each item in the array.
The subscript variable name of the current item of the default array defaults to index, and the variable name of the current item of the array defaults to item

<view wx:for="{
   
   {array}}">
  {
   
   {index}}: {
   
   {item.name}}
</view>

The list data defined in js is as follows

Page({
  data: {
    array: [{
      name: '编程小石头',
    }, {
      name: '邱石'
    }]
  }
})

6-7, continue and break learning

Both continue and break are used to terminate the loop, the difference is that

  • continue: It is to terminate a certain time in the loop and continue to execute the following loop
  • beak: directly terminate the execution of the entire loop, the entire loop is not executing

Seven, array learning

7-1, the concept of array

An array is a collection of data, and more data can be stored in a single variable.
Arrays can store various types of data.
Such as: var names=['programming small stone',16,true]

7-2, two ways to create an array

  • 1. Use new to create an array (not commonly used)
var names=new Array(); 
names[0]="编程小石头";       
names[1]="刘德华";
names[2]="周杰伦";
  • 2. Use array literals to create arrays (commonly used)
var names=['编程小石头','刘德华','周杰伦']

It is obvious that the second way to create an array is more concise than the first one, so we will use the second way to create an array in the future

7-3, get array elements

We get the array elements through the array subscript, which is also called the index, and the subscript of the array starts from 0. As shown in the figure below,
the array can be accessed, set, and modified by subscripting the corresponding element value. We can
get the elements in the data by means of array name[subscript].
For example, names[0] can get the first element in the names array 'programming small stone'

7-4, Calculate the sum and average of the array

We have already learned how to traverse the array before. If I ask you to find the sum and average of all the elements in the array, do you know how to find it?

  • Homework
    Known array [1,2,3,4,5,6] If you calculate the sum and average of this array through code.

7-5, find the maximum value in the array

var nums=[1,2,3,4] In this array, we can clearly see that 4 is the maximum value in the array, but if there are many elements in our array, you may not be able to find out quickly at this time The maximum value is reached, so if we want to find the maximum value in the array, we need to let the code realize it, instead of looking at it with the naked eye.

  • Idea
    In fact, we look for the maximum value in the array, which is a bit similar to a martial arts competition.

    We first compare the first one with the second one. The winner is in the undecided seat, and then the third one will challenge the winner, which will produce a new winner. The winner, and then the following elements will challenge the winner one by one until the last winner is the maximum value we are looking for. And such a one-v-one duel can just be realized with the help of our cycle.
    var nums = [1, 2, 3, 4, 5]
    var max = nums[0]
    for (var i = 1; i < nums.length; i++) {
      if (max < nums[i]) {
        max = nums[i]
      }
    }
    console.log('最大值', max)  //可以得出最大值是5

7-5, add new elements to the array

The push() method can add one or more elements to the end of the array, so when we generally add elements to the array, we can just use the push method directly.

    var nums = [1, 2, 3, 4, 5]
    nums.push(6)
    nums.push(7, 8)
    console.log(nums) //追加新元素后的数组  [1, 2, 3, 4, 5, 6, 7, 8]

7-6, delete the specified element in the array

If we want to delete the specified elements in the array, we can use a new array to accept the elements that meet the requirements, and do not accept the elements that do not meet the requirements, so that the effect of deleting the elements of the array can be achieved

	// 把元素5删除
    var nums = [1, 2, 3, 4, 5]
    //1,定义一个新数组
    var newNums = []
    //2,遍历旧数组
    for (var i = 0; i < nums.length; i++) {
      //3,把符合要求的元素添加到新的数组里
      if (nums[i] !== 5) {
        newNums.push(nums[i])
      }
    }
    console.log(newNums) //删除成功 [1, 2, 3, 4]

Eight, object learning

8-1, what is an object

Objects are just a special kind of data. An object is an unordered set of related properties and methods. The key here is to remember the two new concepts of attributes and methods

  • Attributes: the characteristics of things, the attributes in the object are used to express the characteristics of the object
  • Method: The behavior of things. The method in the object is used to indicate which behaviors the object has.

For example:
Brother Stone has attributes such as name, age, height, weight, etc.
Brother Stone has behaviors such as writing code, singing, cycling, running, and eating.

  • The phone has the following properties and methods

8-2, why do we need objects

When we save one data, we can use variables, and when we save multiple data, we can use arrays. But what if I want to save a complete three-dimensional information.

  • For example, save the complete information of Brother Stone.
    If we use an array to represent it,
    var shitouge=['Programming Little Stone','Male','128','180']
    In this way, even though I have saved the complete information of Brother Stone in the array, I can roughly guess which data What does it mean, but what do the 128 and 180 behind it mean? ? ?

But what if we use objects to store this information?

{
姓名:'编程小石头',
性别:'男'
体重:128
身高:180
}

In this way, can we know what each data means three-dimensionally? This is why we use objects. The above {} wraps some properties of our object. It's just that we don't advocate using Chinese characters for our attribute names, and should use English or pinyin. I wrote it here for the convenience of everyone's understanding.

8-3, Three ways to create objects

  • Create objects using literals
  • Create objects using new Object
  • Create objects using constructors

8-3-1, using literals to create objects

The syntax is as follows
var object name = { property name: property value, property name: property value, method name: function(){} }



Examples are as follows:

var Person = {
 name:'编程小石头',
 age:18,
 code:function(){console.log('石头哥会写代码')}
}

8-3-2, use new Object to create objects

Syntax:
var obj = new Object();
obj.name='programming small stone'
obj.age=18
Here we use new Object() to create an empty object first, and then add attributes and method

8-3-3, Create objects using constructors

A constructor is a special function that is mainly used to initialize objects. It is always used with the new operator. We can extract some public properties and methods in the object and encapsulate them into this function to facilitate batch creation of objects. .

Pay attention to the following points when using constructors to create objects

  • 1. The first letter of the constructor name is customarily capitalized
  • 2. The result can be returned without return in the constructor
  • 3. When calling the constructor to create an object, you must use new
  • 4. We must add this in front of our properties and methods

A complete example is as follows:

	function Person(name, age) {//创建构造函数Person
      this.name = name;
      this.age = age;
      this.action = function (jineng) {
        console.log(name + "具备" + jineng + '的技能')
      }
    }
    //创建对象1
    var obj1 = new Person('编程小石头', 18)
    console.log(obj1.name)//编程小石头
    obj1.action('写代码')//编程小石头具备写代码的技能
     //创建对象2
    var obj2 = new Person('周杰伦', 41)
    console.log(obj2.name)//周杰伦
    obj2.action('唱歌')//周杰伦具备唱歌的技能

Constructors and objects

Our constructors here are like the design drawings of a car. What attributes and methods the car has have been designed on the drawings in advance. We only need to create an object based on the drawing, for example, we can create a new BMW. The car can also be a new Lamborghini.

8-3-4, new keyword execution process

As above, we pass the constructor new an object

	function Person(name, age) {//创建构造函数Person
      this.name = name;
      this.age = age;
      this.action = function (jineng) {
        console.log(name + "具备" + jineng + '的技能')
      }
    }
    //创建对象1
    var obj1 = new Person('编程小石头', 18)

Here, the following four things will be performed when a new object comes out

  • 1. Create an empty object in computer memory
  • 2. Let this point to this new object
  • 3. Execute the code in the constructor and add properties and methods to the new object
  • 4. Return this new object such as obj1 above is the new object we created

8-3-5, variable, attribute, function, method summary

Properties and variables:

  • The same point:
    both are used to store data.
  • The difference:
    Variables are declared and assigned separately, and the variable name can be used directly when used;
    properties in the object do not need to be declared, and when used, use: object.property name.
var dog = {
    //属性
    name:'可可',
    age:'12'
} 
//变量
var num = 12;

//调用变量:(直接使用变量名进行调用)
console.log(num); 
//调用属性:(对象名.属性名)
console.log(dog.name);

Functions and methods:

  • The same point:
    they all achieve a certain function.
  • The difference:
    the function is declared and called separately, and the calling method: the function name ()
    method exists in the object. Call method: object name. method ()
var dog = {
    name:'可可',
    age:'12',
    //方法
    skill:function(){
        console.log('汪汪汪');
    }
}
 
//函数
function skillDemo(){
    console.log("睡觉");
}

//调用函数:(直接使用:函数名(),进行调用)
skillDemo();
//调用方法:(--对象名.方法名()--)
console.log(dog.skill());

8-4, the use of objects

8-4-1, access to the properties of the object

There are two syntaxes for calling object properties

  • object-name.property-name
  • ObjectName['PropertyName']

If our object is as follows

var obj = {
 name:'编程小石头',
 age:18,
 code:function(){console.log('石头哥会写代码')}
}

Calling the name attribute is obj.name,
where obj is our object, and name is the attribute of our object, in obj.name. It is equivalent to the name of obj in translation.
Another way to call attributes is obj['name ']

8-4-2, methods of accessing objects

There is only one way to call a method in an object: object name. method name () The pair of parentheses here are essential.
If our object is as follows

var obj = {
 name:'编程小石头',
 age:18,
 code:function(){console.log('石头哥会写代码')}
}

obj.code() is to directly call the code method in obj

Nine, the learning of built-in objects

9-1, what is a built-in object

Built-in objects refer to some objects that come with Javascript for developers to use. These objects provide some common functions. Developers can easily use these built-in objects without caring about the implementation principles of these built-in objects.
It's like we use the built-in text messaging and calling functions of mobile phones. When we use them, we can use them quickly and conveniently without caring about the implementation principle of making calls. This is why we use built-in objects, mainly for quick and easy use of built-in objects

Common built-in objects are Math, Array, Date, etc.

9-2, Learning to consult documents

Because there are too many methods of built-in objects, it is impossible for us to write down all the methods, so we need to consult the documentation from time to time, just like we look up the dictionary.
Commonly used learning documents are as follows

  • MDN
    official address: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
  • W3cschool
    https://www.w3school.com.cn/js/index.asp
  • Rookie Tutorial
    https://www.runoob.com/js/js-tutorial.html

It is recommended that you use the MDN documentation here. Because this document is relatively complete, it can be quickly retrieved

9-3, Math object learning

Unlike other built-in objects, Math is not a constructor object. All properties and methods of Math are static. The way to quote pi is Math.PI, and the way to call the sine and cosine function is Math.sin(x), where x is the parameter to be passed in. That is to say, our Math can call its properties and methods directly through Math.

Since there are many methods of the Math object, I will only explain some methods commonly used in the development process.

9-3-1, Common attributes of Math

  • Math.PI
    pi, the ratio of the circumference and diameter of a circle, approximately equal to 3.14159

9-3-2, Math commonly used methods

  • Math.abs(x) returns the absolute value of a number
Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs("string"); // NaN
Math.abs();         // NaN
  • Math.max() returns the maximum value of multiple values
    console.log(Math.max(1, 2, 3)) //3
  • Math.min() returns the minimum value of multiple values
  console.log(Math.min(1, 2, 3)) //1

9-3-3, three methods of taking integers in Math

  • Math.ceil(x) Round up, take the bigger one
	console.log(Math.ceil(1.2))//2
    console.log(Math.ceil(1.5))//2
    console.log(Math.ceil(1.7))//2
    console.log(Math.ceil(1.9))//2
  • Math.floor(x) round down, take the smaller one
    console.log(Math.floor(1.2))//1
    console.log(Math.floor(1.5))//1
    console.log(Math.floor(1.7))//1
    console.log(Math.floor(1.9))//1
  • Math.round(x) rounds to an integer
    console.log(Math.round(1.2))//1
    console.log(Math.round(1.5))//2
    console.log(Math.round(1.7))//2
    console.log(Math.round(1.9))//2

9-3-4, learning of random numbers

Math.random() gets a random number greater than or equal to 0 and less than 1
to use.

Usage scenario : Generally, we use random numbers when doing lottery draws

  • Get a random number between two numbers (greater than or equal to min less than max)
//这个随机数可能是整数,也可能是小数
Math.random() * (max - min) + min
  • Get a random integer between two numbers (greater than or equal to min, less than max)
// 这个随机数是min和max之间的随机整数
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  //不含最大值,含最小值
  return Math.floor(Math.random() * (max - min)) + min; 
}
  • Get a random integer between two numbers, including two numbers (greater than or equal to min, less than or equal to max)
// 这个随机数是min和max之间的随机整数
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  //含最大值,含最小值 
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

9-4, Learning of Date object

Our Date object is a constructor object, and we must use the new object to create the object we want to use before we can use it.

The only way to create a new Date object is through the new operator,
for example: let now = new Date()

Usage scenarios such as our seckill countdown, the displayed date needs to use the Date date object

9-4-1, create a Date object

There are 4 ways to create a new date object:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(dateString)
new Date(milliseconds)
  • new Date() creates a Date object
    var d = new Date()
    console.log(d)//Mon Dec 21 2020 20:02:54 GMT+0800 (中国标准时间)

The directly created return is the current time. As shown in the above comment, I am currently at 20:02:54 on December 21, 2020. What you print should be your own current time.

  • new Date(year, month, …)
    new Date(year, month, …) Creates a new Date object with the specified date and time.
    The 7 digits specify the year, month, day, hour, minute, second, and millisecond (in that order):
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
console.log(d) //Mon Dec 24 2018 10:33:30 GMT+0800 (中国标准时间)

One caveat here: JavaScript counts months from 0 to 11. January is 0. December is 11.
4 digits specify year, month, day and hour:

var d = new Date(2018, 11, 24, 10);

3 digits specify year, month and day:

var d = new Date(2018, 11, 24);
  • new Date(dateString)
    new Date(dateString) Create a new date object from a date string
    We can get a Date object by year-month-day or year/month/day
//如我们用两种方式来创建2020年12月21日
    var d1 = new Date(2020,11,21);//月份是从0开始的 11代表12月
    console.log(d1) //Mon Dec 21 2020 00:00:00 GMT+0800 (中国标准时间)
    var d2 = new Date('2020-12-21');
    console.log(d2) //Mon Dec 21 2020 08:00:00 GMT+0800 (中国标准时间)
     var d3 = new Date('2020/12/21');
    console.log(d3) //Mon Dec 21 2020 08:00:00 GMT+0800 (中国标准时间)
  • new Date(milliseconds)
    new Date(milliseconds) Creates a new Date object with zero hours plus milliseconds
    JavaScript stores dates as the number of milliseconds since January 1, 1970, 00:00:00 UTC (Coordinated Universal Time).
    Zero time is January 1, 1970 00:00:00 UTC.
    The current time is: 1608553621233 milliseconds after January 1, 1970 as
    follows
    var d1 = new Date(0);
    console.log(d1) //Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)

r If we want to get the millisecond value between the current time and January 1, 1970, we can

    var d1 = new Date();
    console.log(d1.getTime()) //1608553621233
    var d2 = new Date();
    console.log(d2) //Mon Dec 21 2020 20:27:01 GMT+0800 (中国标准时间)

It can be seen that the millisecond value between the current time and January 1, 1970 is 1608553621233
, then we directly obtain the date from new Date (1608553621233) as follows

    var d1 = new Date(1608553621233);
    console.log(d1) //Mon Dec 21 2020 20:27:01 GMT+0800 (中国标准时间)

So the current date and the current time can be obtained through new Date (the millisecond value of the current date from January 1, 1970). The two can be converted into each other.

9-4-2, date acquisition method

The get method is used to get a part of a date (information from a date object). The following are the most common methods

method describe
getDate() Returns the day as a numeric value (1-31)
getDay() Get the week name as a value (0-6)
getFullYear() Get the four-digit year (yyyy)
getHours() Get hour (0-23)
getMilliseconds() Get milliseconds (0-999)
getMinutes() Get points (0-59)
getMonth() Get the month (0-11)
getSeconds() Get seconds (0-59)
getTime() Get time (from January 1, 1970 to present)

9-4-3, date setting method

The setter method is used to set a part of the date

method describe
setDate() Set the day as a value (1-31)
setFullYear() Set year (month and day optional)
setHours() set hour (0-23)
setMilliseconds() Set milliseconds (0-999)
setMinutes() Set points (0-59)
setMonth() set month (0-11)
setSeconds() Set seconds (0-59)
setTime() Set time (milliseconds since January 1, 1970)

9-4-4, countdown (comprehensive case)

Here we will take you to implement a countdown case. For example, we know the end time of an event, and then calculate how long the event will end. I will lead you to write a comprehensive case in the video. You can follow the video lesson to learn this comprehensive case.

9-5, Learning of Array array objects

The purpose of the array object is to use a single variable name to store a series of values.
As I learned about arrays before, a way to create arrays

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

9-5-1, judge whether it is an array

There are two ways to determine whether an object is an array

  • 1, through instanceof Array
  • 2. Through the Array.isArray() method
    var arr = new Array()
    console.log(arr instanceof Array) //true
    console.log(Array.isArray(arr))//true

9-5-2, Add and delete array elements

In fact, we taught you how to add and delete arrays in the section explaining arrays. Today, we will show you how to add and delete arrays systematically.

  • push方法添加
    在数组的末尾添加一个或者多个元素
  • unshift方法添加
    在数组的开头添加一个或者多个元素
  • pop方法删除
    删除数组尾部的元素,一次只能删除一个
  • shift方法删除
    删除数组最前面(头部)的元素

9-5-3,配套练习(筛选数组)

给你一组数据 [20,59,40,80,99,98] 筛选出所有小于60的数组,可以理解为找到所有不及格的学生的成绩,你会怎么做呢? 可以结合我们上面学过的知识,自己思考下。我会在视频里带着你写一遍。看视频之前,建议你自己先思考下。

9-5-4,reverse方法翻转数组

reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。

    var arr = [1, 2, 3, 4, 5]
    console.log(arr.reverse())//[5, 4, 3, 2, 1]

9-5-5,sort方法对数组进行排序

用sort方法进行排序,默认是升序排列的,如下

   var arr = [1, 3, 2, 5, 4]
   console.log(arr.sort())//[1, 2, 3, 4, 5]

但是直接用sort方法会有问题

    var arr = [11, 3, 22, 55, 44]
    console.log(arr.sort())//[11, 22, 3, 44, 55]

为什么会出现3在11和22后面的问题呢,因为我们sort默认排序顺序是在将元素转换为字符串,然后对字符串进行比较,再排序的,所以我们要想用sort来排序,就要用到另外一个写法了

    var arr = [11, 3, 22, 55, 44]
    //按照升序排序
    arr.sort(function (a, b) {
      return a - b
    })
    //按照降序排序
    arr.sort(function (a, b) {
      return b - a
    })

上面的 写法是固定的,大家只需要记住就行了。 a-b时是升序,b-a时是降序

function (a, b) {
      return a - b 
}

9-5-6,数组的索引方法

  • indexOf()方法
    返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
  • lastIndexOf() 方法
    返回指定元素在数组中的最后一个的索引,如果不存在则返回 -1

9-5-7,课程作业,对数组进行去重

给出一个数组 [1,3,5,2,4,5,6,4],现要求把数组里重复的元素给删除掉,我会在视频里带着大家写一遍,在看视频之前,建议大家先自己仔细思考下,最好自己先实现一下。

9-5-7, convert the array to a string

We convert an array to a string in the following two ways

  • toString()
    concatenates the arrays into a string with commas.
  • join(delimiter)
    connects the arrays into a string through the delimiter. If the delimiter in the join is not written, commas are used by default to connect the array elements to form a string
    var arr = [1, 3, 2, 5, 4]
    console.log(arr.toString())//1,3,2,5,4
    console.log(arr.join('-'))//1-3-2-5-4

Here I hope everyone will focus on it, because in our actual development, we will convert the array into a string and pass it to the background developer.

9-5-8, other common methods of arrays

  • The concat() method
    is used to combine two or more arrays. This method does not change the existing array, but returns a new array
  • The slice() method
    intercepts a part of the array and returns a new array object, which is a shallow copy of the original array determined by begin and end (including begin, excluding end). The original array will not be changed
  • The splice() method modifies or deletes the array splice
    by deleting or replacing existing elements or adding new elements in place (starting from the number, delete a few)
    var arr = [1, 2, 3, 4, 5]
    arr.splice(0, 2)// 从索引为0的地方开始,删除2个元素。
    console.log(arr) //[3, 4, 5]
  • splice (starting from the number, how many to replace, the value to be replaced)
    var arr = ['a', 'b', 'c', 'd', 'e']
    arr.splice(0, 2,'A','B')// 从索引为0的地方开始,替换2个元素,替换为 A和B
    console.log(arr) //["A", "B", "c", "d", "e"]

At this point, we have almost finished learning the knowledge of JavaScript. Whether it is in a small program or in a uniapp, the code of the js part is basically the same. Therefore, if you learn js well, you can travel all over the world without fear.

Guess you like

Origin blog.csdn.net/qiushi_1990/article/details/128035694