JavaScript-[Week 1]

文章来源于网上收集和自己原创,若侵害到您的权利,请您及时联系并删除~~~

Introduction to JavaScript
Basic concepts such as variables, constants, data types, operators, etc.
Can realize the conversion of data types, and how to program in combination with the four arithmetic operations.

  • Understand the relationship between things in the real world and computers
  • Understand what data is and know its classification
  • Understand the "container" in which variables store data
  • Master the use of common operators and understand precedence relationships
  • Know the characteristics of implicit conversion of JavaScript data types

1 Introduction

1.1 What is JavaScript?

What is JavaScript?
It is a programming language that runs on the client (browser) to achieve human-computer interaction. (P4)

Function (What to do?)

The composition of JavaScript

Insert image description here

  • ECMAScript: stipulates the core knowledge of js basic syntax. For example: variables, branch statements, loop statements, objects, etc.

  • Web APIs :

    DOM manipulation documents, such as moving, resizing, adding and deleting page elements, etc.

    BOM operates the browser, such as page pop-ups, detecting window width, storing data to the browser, etc.

JavaScript authoritative website: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript

summary:

  1. What is JavaScript?

    JavaScript is a programming language that runs on the client (browser)

  2. What does JavaScript consist of?

    ECMAScript (basic syntax), web APIs (DOM, BOM)

Experience:
Case of clicking the switch button - experience HTML+CSS+JS to achieve interactive effects
Insert image description here

1.2 Introduction method

Master the introduction method of JavaScript and initially understand the role of JavaScript
Insert image description here

A JavaScript program cannot run independently, it needs to be embedded in HTML before the browser can execute the JavaScript code. scriptThere are three ways to introduce JavaScript code into HTML through tags:

1.2.1 Internal method (embedded)

scriptWrap JavaScript code through tags
Write directly in the html file and wrap it with script tags
Specification: script tags are written on it
Extension: alert('Hello, js') The page pops up an alert dialog box

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
  <!-- 内联形式:通过 script 标签包裹 JavaScript 代码 -->
  <script>
    alert('嗨,欢迎来前端技术!')
  </script>
</body>
</html>

注意

  • The reason we <script>put it near the bottom of the HTML file is that browsers load the HTML in the order the code is in the file.
  • If the JavaScript loaded first expects to modify the HTML below it, it may fail because the HTML has not yet been loaded.
  • Therefore, placing JavaScript code near the bottom of an HTML page is usually the best strategy.

1.2.2 External form (external link type)

Generally, JavaScript code is written in a separate file ending with .js, and then introduced through the attribute scriptof the tag.src

// demo.js
document.write('嗨,欢迎来前端技术!')
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
  <!-- 外部形式:通过 script 的 src 属性引入独立的 .js 文件 -->
  <script src="demo.js"></script>
</body>
</html>

注意: If the script tag uses the src attribute to introduce a .js file, the code of the tag will be ignored! ! ! As shown in the following code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
  <!-- 外部形式:通过 script 的 src 属性引入独立的 .js 文件 -->
  <script src="demo.js">
    // 此处的代码会被忽略掉!!!!
  	alert(666);  
  </script>
</body>
</html>

1.2.3 Inline style

The code is written inside the tag.
Note: This is just for understanding, but the vue framework will use this mode later.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
   
  <button onclick="alret('逗你玩儿')"></button>
</body>
</html>

Summary

  1. Three writing positions for JavaScript?

    internal

    external

    Inside the industry

  2. Precautions:

    Try to write to the end of the document </body>and to the front.

    Do not write code in the middle of external js tags, otherwise it will be ignored

Exercise 1

Requirement: Please use both external and internal JavaScript writing methods. The page will pop up:Work hard
Time: 5 minutes
外部:

  1. Create a new js file false --> Create a new my.js file
alert('努力奋斗')
  1. Referenced in html file
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
	<script src="../js/my.js"></script> 
</body>
</html>

内部:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
     alert("努力,奋斗")
  </script>
</body>
</html>

1.3 Comments and terminators

You can block code execution or add comment information through comments. JavaScript supports two forms of comment syntax:

1.3.1 Single-line comments

Use // to comment a single line of code

Function: // The code on the right line will be ignored

hot key:ctrl + /

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 注释</title>
</head>
<body>
  
  <script>
    // 这种是单行注释的语法
    // 一次只能注释一行
    // 可以重复注释
    document.write('嗨,欢迎学习前端技术!');
  </script>
</body>
</html>

1.3.2 Multi-line comments

Use /* */to comment multiple lines of code

Effect: Everything between /* and */ will be ignored

hot key:shift + alt + A

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 注释</title>
</head>
<body>
  
  <script>
    /* 这种的是多行注释的语法 */
    /*
    	更常见的多行注释是这种写法
    	在些可以任意换行
    	多少行都可以
      */
    document.write('嗨,欢迎学习前端技术!')
  </script>
</body>
</html>

1.4 Terminator

In JavaScript, ;it represents the end of a piece of code. In most cases, it can be omitted and ;replaced by carriage return (enter).

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 结束符</title>
</head>
<body>
  
  <script> 
    alert(1);
    alert(2);
    alert(1)
    alert(2)
  </script>
</body>
</html>

In actual development, many people advocate omitting the terminator when writing JavaScript code;

Agreement: In order to unify the style, the ending symbol must be written in every sentence or not written in every sentence (according to the team's requirements.)

summary:

  1. What are the two ways of commenting in JavaScript?

    Single line comment //

    Multi-line comments /* */

  2. Notes on JavaScript terminators

    The terminator is a semicolon;

    Can the terminator be omitted? Yes

    But for the sake of unified style, the ending symbol must be written in every sentence or not written in every sentence.

1.5 Input and output

Output and input can also be understood as the interaction between human and computer. The user inputs information to the computer through the keyboard, mouse, etc., and the computer processes and then displays the result to the user. This is a process of input and output.

For example: if you press the arrow keys on the keyboard, the up/down keys can scroll the page, the action of pressing the up/down keys is called input, and the scrolling of the page is called output.

1.5.1 Output

JavaScript can receive user input and then output the input results:

alert()document.wirte()console.log()

Take numbers as an example. If you enter any number into alert()or , it will be displayed (output) to the user in the form of a pop-up window.document.write()

1.5.2 Input

Inputting prompt()any content to will appear in the browser in the form of a pop-up window, generally prompting the user to enter some content.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 输入输出</title>
</head>
<body>
  
  <script> 
    // 1. 输入的任意数字,都会以弹窗形式展示
    document.write('要输出的内容')
    alert('要输出的内容');

    // 2. 以弹窗形式提示用户输入姓名,注意这里的文字使用英文的引号
    prompt('请输入您的姓名:')
  </script>
</body>
</html>

Exercise 2

Time: 5 minutes
Requirements:

  • A dialog box pops up in the browser: Hello JS~ alert()
  • Print output on the page: Hello JS~ document.write()
  • Page console output: Hello JS~ console.log()
 document.write("你好,js")
 alert("你好,js")
 console.log("你好,js")

JavaScript code execution sequence:

  • Execute JavaScript code in order of HTML document flow
  • alert()and prompt()they will skip page rendering and be executed first (currently for understanding, the detailed execution process will be explained later)

1.6 Literals

Goal: Be able to tell what a literal is.
In computer science, a literal describes something in a computer.
For example:

  • Our salary is: 1000. At this time, 1000 is a numerical literal.
  • 'Student' string literal
  • There are also [] array literals {}, object literals, etc. that we will learn next.

Summarize:

  1. What is JavaScript?

    JavaScript is a programming language that can achieve many web page interaction effects.

  2. Where to write JavaScript?

    Internal JavaScript

    Internal JavaScript – written above the tag

    External JavaScript - but

2. Variables

Understand that variables are "containers" for computer storage of data, and master how to declare variables

Insert image description here

A variable is a "container" used to store data in a computer. It can make the computer have memory. A popular understanding of a variable is to use [a certain symbol] to represent [a specific value] (data)

Insert image description here

Note: Variables are not the data themselves, they are just containers for storing values. It can be understood as cardboard boxes used to hold things.

<script>
  // x 符号代表了 5 这个数值
  x = 5
  // y 符号代表了 6 这个数值
  y = 6
    
  //举例: 在 JavaScript 中使用变量可以将某个数据(数值)记录下来!

  // 将用户输入的内容保存在 num 这个变量(容器)中
  num = prompt('请输入一数字!')

  // 通过 num 变量(容器)将用户输入的内容输出出来
  alert(num)
  document.write(num)
</script>

2.1 Statement

To use a variable, you first need to create it (also called declaring a variable or defining a variable)
let 变量名

Declaring a variable consists of two parts: declaration keyword and variable name (identification)

let is the keyword (let: allow, permit, let, want). The so-called keywords are words provided by the system specifically for declaring (defining) variables.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 声明和赋值</title>
</head>
<body>
  
  <script> 
    // let 变量名
    // 声明(定义)变量有两部分构成:声明关键字、变量名(标识)
    // let 即关键字,所谓关键字是系统提供的专门用来声明(定义)变量的词语
    // age 即变量的名称,也叫标识符
    let age
  </script>
</body>
</html>

Keywords are some built-in English words (words or abbreviations) in JavaScript, which represent certain specific meanings, such as the letmeaning of declaring variables. After seeing , letyou can think that this line of code means declaring variables, such aslet age;

letand varare both keywords for declaring variables in JavaScript. It is recommended to use letto declare variables! ! !

2.2 Assignment

Declaring (defining) a variable is equivalent to creating an empty "container" and adding data to this container through assignment.
After defining a variable, you can initialize it (assign a value). Follow the variable name with "=" and then the value

Insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 声明和赋值</title>
</head>
<body>
  
  <script> 
    // 声明(定义)变量有两部分构成:声明关键字、变量名(标识)
    // let 即关键字,所谓关键字是系统提供的专门用来声明(定义)变量的词语
    // age 即变量的名称,也叫标识符
    let age
    // 赋值,将 18 这个数据存入了 age 这个“容器”中
    age = 18
    // 这样 age 的值就成了 18
    document.write(age)
    
    // 也可以声明和赋值同时进行
    let str = 'hello world!'
    alert(str);
  </script>
</body>
</html>

summary

  1. What keywords are used to declare variables?let
  2. What symbols are used to assign values ​​to variables? = 这个符号我们也称为 赋值运算符
  3. In development, we often declare and assign values ​​directly at the same time?let age = 18

Exercise 3

need:

  1. Declare a variable to store the number of items purchased by the user (num), which is 20 pieces
  2. Declare a variable to store the user's name (uname) as 'Zhang San'
  3. Print the two variables to the console in sequence.
 let num = 18
 let uname = '张三'
 console.log(num,uname)

2.3 Update variables

Insert image description here

2.4 Declare multiple variables

After a variable is assigned a value, you can also update it by simply giving it a different value.

let age = 18,uname = 'zhangsan'

let age = 18
let uname = 'zhangsan'

//为了更好的可读性,请一行只声明一个变量。

Case 1
Requirements: A dialog box pops up in the browser: Please enter your name. Output on the page: The name you just entered.
Analysis:

  • ①: Input: User input box: prompt()
  • ②: Internal processing: saving data
  • ③: Output: Page printing, document.write()
  let a = "zhangsan"
  document.write("你输入的姓名为:",a)

Case 2
Requirement:
There are 2 variables: num1 contains 10, and num2 contains 20

Finally, it becomes num1, which contains 20, and num2, which contains 10.

Purpose:

  1. Practice using variables
  2. Prepare for bubble sorting later

Insert image description here

  let num =20,num3=21
  let num2 = 21
  let temp 
  temp = num1
  num1 = num2
  num2 = temp
  console.log(num1,num2)

2.5 The nature of variables

Memory: the place where data is stored in the computer, which is equivalent to a space.
The nature of variables: it is a small space that the program applies for in the memory to store data.

Insert image description here

2.6 Keywords

JavaScript uses special keywords letand varto declare (define) variables, and you need to pay attention to some details when using them:

The following are letthings to note when using:

  1. Allow declaration and assignment to occur simultaneously
  2. Duplicate declarations are not allowed
  3. Allows multiple variables to be declared and assigned values ​​at the same time
  4. Some keywords built into JavaScript cannot be used as variable names

The following are varthings to note when using:

  1. Allow declaration and assignment to occur simultaneously
  2. Duplicate declarations allowed
  3. Allows multiple variables to be declared and assigned values ​​at the same time

letThere is not much difference between using and in most cases var, but letit is varmore rigorous than using , so it is recommended to use let. The difference between the two will be further introduced later.

2.7 Variable name naming rules

There are a series of rules that need to be followed regarding variable names (identifiers):

  1. It can only be letters, numbers, underscores, $, and it cannot start with a number.
  2. Letters are case-sensitive, such as Age and age are different variables
  3. JavaScript internal used words (keywords or reserved words) are not allowed
  4. Try to ensure that the variables have certain semantics, and you can know the meaning by looking at the words.

specification:

  • The name should be meaningful

  • Follow little camel case nomenclature

    The first letter of the first word is lowercase, and the first letter of each subsequent word is uppercase. Example: userName

Note: The so-called keywords refer to words used internally in JavaScript, such as letand var, and reserved words refer to words that are not currently used within JavaScript, but may be used in the future.

Insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 变量名命名规则</title>
</head>
<body>
  
  <script> 
    let age = 18 // 正确
    let age1 = 18 // 正确
    let _age = 18 // 正确

    // let 1age = 18; // 错误,不可以数字开头
    let $age = 18 // 正确
    let Age = 24 // 正确,它与小写的 age 是不同的变量
    // let let = 18; // 错误,let 是关键字
    let int = 123 // 不推荐,int 是保留字
  </script>
</body>
</html>

Exercise 4

Requirement: Allow users to input their name, age, gender, and then output to the web page
Analysis:

  • ①: Pop-up input box (prompt): Please enter your name (uname): Save it with a variable.

  • ②: Pop-up input box (prompt): Please enter your age (age): Save it with a variable.

  • ③: Pop-up input box (prompt): Please enter your gender (gender): Save it with a variable.

  • ④: The page outputs (document.write) the 3 variables just now

  let uname = prompt("请输入姓名")
  let age = prompt("请输入你的年龄")
  let gender = prompt("请输入你性别")
  document.write(uname,age,gender)

3. Constants

Concept: Variables declared using const are called "constants".

Usage scenario: When a variable will never change, you can use const to declare it instead of let.

Naming convention: consistent with variables

const PI = 3.14

Note: Constants are not allowed to be reassigned and must be assigned (initialized) when declared.

Insert image description here

let — now actually develops variable declarations.

var — The previous way of declaring variables had many problems.

const — Similar to let, but the value of the variable cannot be modified.

4. Data type

Everything in the computer world is data.

Tell me what are the basic data types in JS?

  • Basic data types
  • Reference data type

Insert image description here

Computer programs can process large amounts of data. In order to facilitate data management, the data is divided into different types:

4.1 Numeric type (Number)

That is, the numbers we learn in mathematics can be integers, decimals, positive numbers, and negative numbers

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 数据类型</title>
</head>
<body>
  
  <script> 
    let score = 100 // 正整数
    let price = 12.345 // 小数
    let temperature = -40 // 负数

    document.write(typeof score) // 结果为 number
    document.write(typeof price) // 结果为 number
    document.write(typeof temperature) // 结果为 number
  </script>
</body>
</html>

Numerical types in JavaScript are the same as numbers in mathematics, divided into positive numbers, negative numbers, decimals, etc.

注意事项

  • JS is a weak data type, which type the variable belongs to, we can only confirm it after assignment
  • Java is a strong data type such as int a = 3 must be an integer

Numbers can have many operations, such as multiplication *, division /, addition +, subtraction -, etc., so they are often used together with arithmetic operators.

Mathematical operators are also called arithmetic operators, which mainly include addition, subtraction, multiplication, division, and remainder (modulo).

+: Sum
-: Difference
*: Product
/: Quotient
%: Modulo (remainder): often used in development as whether a number is divisible

Goal: Be able to tell the priority order of execution of JavaScript arithmetic operators

When a program is written using multiple operators at the same time, they will be executed in a certain order, which is called priority.

In JavaScript, the higher the priority, the first to be executed. When the priorities are the same, they are executed from left to right.

  • Multiplication, division, and remainder have the same priority.

  • Addition and subtraction have the same priority

  • Multiplication, division, and remainder have higher priority than addition and subtraction.

  • Use () to increase the priority

  • Summary: Multiply and divide first, then add and subtract. If there are parentheses, calculate the ones in the parentheses first~~~

Exercise 5

Requirement: Enter the radius of the circle in the dialog box, calculate the area of ​​the circle and display it on the page
. Analysis:

  • ①: Mathematical formula of area: π*r²
  • ②: Convert to JavaScript writing: variable * r * r
const PI = 3.14
let r = +prompt('请输入半径:')
let s = PI * r * r
document.write("圆的面积是",s)
console.log(PI)

NaN represents a calculation error. It is the result of an incorrect or undefined mathematical operation

NaN is sticky. Any operation on NaN will return NaN

console.log('老师' - 2) // NaN
console.log(NaN + 2) // NaN

4.2 String type (string)

Data wrapped in single quotes ( ''), double quotes ( "") or backticks are all called strings. There is no essential difference between single quotes and double quotes. Single quotes are recommended.

Precautions:

  1. Whether single quotes or double quotes must be used in pairs
  2. Single quotes/double quotes can be nested within each other, but not within themselves.
  3. You can use escape characters if necessary \to output single or double quotes.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 数据类型</title>
</head>
<body>
  
  <script> 
    let user_name = '小明' // 使用单引号
    let gender = "男" // 使用双引号
    let str = '123' // 看上去是数字,但是用引号包裹了就成了字符串了
    let str1 = '' // 这种情况叫空字符串
		
    documeent.write(typeof user_name) // 结果为 string
    documeent.write(typeof gender) // 结果为 string
    documeent.write(typeof str) // 结果为 string
  </script>
</body>
</html>

String concatenation:

Scenario: The + operator can concatenate strings.

Mantra:数字相加,字符相连

let uanme = '薛之谦'
let song = '认真的雪'
documeent.write(uname + song)  // 薛之谦认真的雪

4.3 Template string

Concatenate strings and variables

Before it was available, it was troublesome to splice variables

documeent.write('大家好,我叫'+ uname + '练习' + age + '年')  

grammar

  • `` (backtick)
  • In English input mode, press the key above the tab key on the keyboard (the key to the left of 1)
  • When splicing content into variables, use ${ } to wrap the variables
documeent.write(`大家好,我叫${
      
      uname}练习${
      
      age}`)  

Exercise 6

Requirement: A dialog box pops up on the page, enter the name and age, and the page displays: Hello everyone, my name is xxx, and I am xx years old this year

let name = prompt('请输入您的名字')
let age =  prompt('请输入您的年龄')
documeent.write(`大家好,我叫${
      
      name},今年${
      
      age}岁了`)  

4.4 Boolean type (boolean)

When expressing affirmation or negation, it corresponds to Boolean data in the computer, which has two fixed values true​​and false, which are used for affirmative data trueand negative data false.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 数据类型</title>
</head>
<body>
  
  <script> 
    //  pink老师帅不帅?回答 是 或 否
    let isCool = true // 是的,摔死了!
    isCool = false // 不,套马杆的汉子!

    document.write(typeof isCool) // 结果为 boolean
  </script>
</body>
</html>

4.5 Undefined type (undefined)

Undefined is a relatively special type. There is only one value undefined, and only the variable is declared. If no value is assigned, the default value of the variable is undefined. Generally, it is rare to directly assign a value to a variable as undefined.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 数据类型</title>
</head>
<body>
  
  <script> 
    // 只声明了变量,并末赋值
    let tmp;
    document.write(typeof tmp) // 结果为 undefined
  </script>
</body>
</html>

Note: The value of a variable in JavaScript determines the data type of the variable.

Work usage scenarios:

  • In our development, we often declare a variable, waiting for the data to be transmitted.
  • If we don't know whether the data has been passed, we can judge whether the user has passed the data by checking whether the variable is undefined

4.6 Empty type (null)

null in JavaScript is just a special value representing "nothing", "empty" or "value unknown"

let obj = null
console.log(obj) // null

The difference between null and undefined:

  • undefined means no assignment
  • null means a value is assigned, but the content is empty

null Usage scenarios in development:

  • Official explanation: treat null as an object that has not yet been created
  • Vernacular: In the future, there will be a variable that stores an object, but the object has not been created yet. You can give it a

5. Type conversion

Understand the characteristics of weakly typed languages ​​and master the method of explicit type conversion

In JavaScript, data is divided into different types, such as numerical values, strings, Boolean values, and undefined. In the actual programming process, there is a conversion relationship between different data types.

Why type conversion is needed?
JavaScript is a weak data type: JavaScript does not know what data type the variable belongs to. It only knows when it is assigned a value.

Pitfalls: The data obtained using forms and prompts is of string type by default. At this time, simple addition operations cannot be performed directly.

: Detect data type through typeof keyword

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 数据类型</title>
</head>
<body>
  
  <script> 
    // 检测 1 是什么类型数据,结果为 number
    document.write(typeof 1)
  </script>
</body>
</html>

5.1 Implicit conversion

When certain operators are executed, the system automatically converts the data type internally. This conversion is called implicit conversion.
rule:

  • +As long as one of the two sides of the number is a string, the other will be converted into a string.
  • Arithmetic operators other than +, such as - * /, etc., will convert data into numeric types.

shortcoming:

  • The conversion type is not clear and can only be summarized based on experience.

Tips:

  • The + sign can be converted into a numeric type when parsed as a positive sign.

  • The result of adding any data to a string is a string

Insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 隐式转换</title>
</head>
<body>
  <script> 
    let num = 13 // 数值
    let num2 = '2' // 字符串

    // 结果为 132
    // 原因是将数值 num 转换成了字符串,相当于 '13'
    // 然后 + 将两个字符串拼接到了一起
    console.log(num + num2)

    // 结果为 11
    // 原因是将字符串 num2 转换成了数值,相当于 2
    // 然后数值 13 减去 数值 2
    console.log(num - num2)

    let a = prompt('请输入一个数字')
    let b = prompt('请再输入一个数字')

    alert(a + b);
  </script>
</body>
</html>

: Implicit conversion of data types is a feature of JavaScript and will be encountered in subsequent studies. For now, you need to understand what implicit conversion is.

5.2 Explicit conversion

It is not strictly prohibited to rely too much on implicit conversions within the system when writing programs, because the rules of implicit conversions are not clear and are mostly based on experience. In order to avoid problems caused by implicit conversion, the root logic usually requires explicit conversion of the data.

5.2.1 Number

By Numberexplicitly converting to a numeric type, when the conversion fails, the result is NaN(Not a Number), that is, it is not a number.

  • Convert to numeric type
  • If there is a non-number in the string content, the result will be NaN (Not a Number) when the conversion fails, which means it is not a number.
  • NaN is also number type data, representing non-number
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 隐式转换</title>
</head>
<body>
  <script>
    let t = '12'
    let f = 8

    // 显式将字符串 12 转换成数值 12
    t = Number(t)

    // 检测转换后的类型
    // console.log(typeof t);
    console.log(t + f) // 结果为 20

    // 并不是所有的值都可以被转成数值类型
    let str = 'hello'
    // 将 hello 转成数值是不现实的,当无法转换成
    // 数值时,得到的结果为 NaN (Not a Number)
    console.log(Number(str))
  </script>
</body>
</html>

5.2.2 parseInt(data)

Keep only integers

5.2.3 parseFloat(data)

Decimals can be retained

5.2.4 Convert to character type

String (database)
variable.toString (base)

Exercise 7

Enter 2 numbers, calculate the sum of the two, and print it to the page

Insert image description here

  let num1 = +prompt('请输入第一个数')
  let num2 =  +prompt('请输入第二个数')
  // num1 = Number(num1)
  // num2 = Number(num2)
  let sum = num1 + num2
  console.log(sum)

Summarize

  1. The concept of type conversion is
    to convert one data type into another type. JavaScript is a weak data type. In many cases, data types need to be converted during calculations.

  2. Implicit conversion:
    the system automatically performs conversion

  3. Explicit conversion:
    Write your own code to tell the system what type to convert to. Number
    If there are non-digits in the string content, you will get NaN.String

6. Practical case - user order information case

Requirement: The user enters the product price, product quantity, and delivery address, and the order information can be automatically printed
. Analysis:

  • ①: 3 data need to be input, so 3 variables are needed to store price num address
  • ②: Need to calculate the total price total
  • ③: Print the page to generate a form and fill it with data.
  • ④: Remember to use template strings

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_44625715/article/details/132644817