JavaScript zero-based customs clearance (4) the data type of the variable,

In the computer, the storage space occupied by different data is different. In order to facilitate dividing the data into data with different required memory sizes and make full use of the storage space, different data types are defined.
Simply put, a data type is a category model of data. For example, the name is "Zhang San" and the age is 18. The types of these data are different.

1.2 Data Types of Variables

Variables are where values ​​are stored, they have names and data types. The data type of a variable determines how the bits representing those values ​​are stored in the computer's memory. JavaScript is a weakly typed or dynamic language. This means that there is no need to declare the type of the variable in advance, and the type will be automatically determined during the execution of the program.

var age = 10;        // 这是一个数字型
var areYouOk = '是的';   // 这是一个字符串     

When the code is running, the data type of the variable is judged by the JS engine according to the data type of the variable value on the right side of =. After running, the data type of the variable is determined.
JavaScript has dynamic typing, which also means that the same variable can be used as different types:
JS has dynamic typing, which also means that the same variable can be used as different types The
same variable can be used as different types

var x = 6;           // x 为数字
var x = "Bill";      // x 为字符串    

JS divides data types into two categories:
simple data types (Number, String, Boolean, Undefined, Null)
complex data types (object)
Number, S, Boolean, Undefined, Null
2.1 Simple data types (basic data types)
insert image description here
Undefined declaration The variable a has not been given a value, at this time a=undefined
2.2 Number Type Number
JavaScript number type can be used to store both integer values ​​and decimal numbers (floating point numbers).

var age = 21; // Integer
var Age = 21.3747; // Decimal
2.2 Number Number

  1. Numerical bases
    The most common bases are binary, octal, decimal, and hexadecimal.
  // 1.八进制数字序列范围:0~7
 var num1 = 07;   // 对应十进制的7
 var num2 = 019;  // 对应十进制的19
 var num3 = 08;   // 对应十进制的8
  // 2.十六进制数字序列范围:0~9以及A~F
 var num = 0xA;   

var num=0xA; At this stage, we only need to remember that in JS, add 0 in front of octal and 0x in front of hexadecimal. In JS, add 0 in front of octal and 0x
in front of hexadecimal
. 2. Numerical range
in JavaScript Maximum and minimum value
alert(Number.MAX_VALUE); // 1.7976931348623157e+308
alert(Number.MIN_VALUE); // 5e-324
MAX_VALUE,
MIN_VALUE
maximum value: Number.MAX_VALUE, this value is: 1.7976931348623157e+308
minimum Value: Number.MIN_VALUE, this value is: 5e-32
3. Three special values ​​of digital type

alert(Infinity);  // Infinity
alert(-Infinity); // -Infinity
alert(NaN);       // NaN

alert(Infinity)
alert(-Infinity)Infinity
Infinity, representing infinity, greater than any value
-Infinity, representing infinitely small, less than any value
NaN, Not a number, representing a non-numerical
NaN, Not a number representing a non-numerical
4. isNaN( ) is
used to determine whether a variable is of a non-numeric type, return true or false
, insert image description here
insert image description here

var usrAge = 21;
var isOk = isNaN(userAge);
console.log(isNum);            // false ,21 不是一个非数字
var usrName = "andy";
console.log(isNaN(userName));  // true"andy"是一个非数字

isNaN()
2.3 String type String
type can be any text in quotation marks, its syntax is double quotation marks "" and single quotation marks ''

var strMsg = "我爱北京天安门~";  // 使用双引号表示字符串
var strMsg2 = '我爱吃猪蹄~';    // 使用单引号表示字符串
// 常见错误
var strMsg3 = 我爱大肘子;       // 报错,没使用引号,会被认为是js代码,但js没有这些语法

''Single quotation marks identify strings
Because attributes in HTML tags use double quotation marks, JS here we recommend using single quotation marks.

  1. String quotes nested
    JS You can use single quotes to nest double quotes, or use double quotes to nest single quotes (outer double inner single, outer single inner double)
var strMsg = '我是"高帅富"程序猿';   // 可以用''包含""
var strMsg2 = "我是'高帅富'程序猿";  // 也可以用"" 包含''
//  常见错误
var badQuotes = 'What on earth?"; // 报错,不能 单双引号搭配
  1. String escape characters
    Similar to special characters in HTML, there are also special characters in strings, which we call escape characters.
    Escape characters all start with \. Commonly used escape characters and their descriptions are as follows:
    insert image description here
    \b space\b space, ]t indentation,
    case: pop-up webpage warning box
    insert image description here
    is unbearably hot, under the hot sun, I stand tall and straight It has become the most unique landscape. I look around, here is my stage, I am the king of heaven and earth. At this moment, I was so arrogant that I finally shouted: "Get the junk~"

3. String length

A string is composed of several characters, and the number of these characters is the length of the string. The length of the entire string can be obtained through the length property of the string.

var strMsg = "我是帅气多金的程序猿!";
alert(strMsg.length); // 显示 11
  1. String splicing
    Multiple strings can be spliced ​​with +. The splicing method is string + any type = new string after
    splicing. Before splicing, any type added to the string will be converted into a string, and then spliced Convert any type added by the torch to the string before splicing into a new
    string, and then splicing it into a new string
//1.1 字符串 "相加"
alert('hello' + ' ' + 'world'); // hello world
//1.2 数值字符串 "相加"
alert('100' + '100'); // 100100
//1.3 数值字符串 + 数值
alert('11' + 12);     // 1112 
  • Number summary formula: add numbers, connect characters
  1. String concatenation enhancement
console.log('pink老师' + 18);           // 只要有字符就会相连 
var age = 18;
// console.log('pink老师age岁啦');       // 这样不行哦
console.log('pink老师' + age);          // pink老师18
console.log('pink老师' + age + '岁啦');  // pink老师18岁啦

We often concatenate strings and variables, because variables can easily modify the value inside.
Variables cannot be quoted, because quoted variables will become strings.
If there are strings on both sides of the variable, the formula " "Citation plus plus", delete the number, and add the variable in the middle.
If there are string concatenations on both sides of the variable, the formula is to cite plus plus, delete the number, and add the variable in the middle
.
age, and then a warning box will pop up to display "You are xx years old this year" (xx represents the age you just entered).
insert image description here
This is a very simple insert image description here
interactive effect program written in JS.
Case Study
Three Essential Elements of Interactive Programming:
Do You Like Me? → This is the user input The
girl thinks about it → This is the internal processing of the program and
finally gave you a slap → This is the output result
So how to implement it in the program?
Pop up an input box (prompt), let the user input the age (user input)
, save the value input by the user in a variable, splicing the age just entered with the string to be output (internal processing of the program)
Use the alert statement to pop up an alert box ( output result)

// An input box (prompt) pops up, allowing the user to enter the age (user input)
// Save the value input by the user in a variable, and splicing the age just entered with the string to be output (internal processing in the program)
// Use The alert statement pops up an alert box (output result)

var age = prompt('Please enter your age');

var str = 'You are this year' + age + 'You are old';

alert(str);
2.5 Boolean Boolean
The boolean type has two values: true and false, where true means true (true) and false means false (false).
When adding a boolean and a number, the value of true is 1 and the value of false is 0.

console.log(true + 1);  // 2
console.log(false + 1); // 1

2.6 Undefined and Null

A variable that is not assigned a value after declaration will have a default value of undefined (if it is connected or added, pay attention to the result).
A variable that is not assigned a value after declaration will have a default value of undefined if it is connected or added, Pay attention to the results

var variable;
console.log(variable);           // undefined
console.log('你好' + variable);  // 你好undefined
console.log(11 + variable);     // NaN
console.log(true + variable);   //  NaN

A variable is declared for null value, and the value stored in it is empty (when learning objects, we continue to study null)
A variable is declared for null value, and the value stored in it is empty

var vari = null;
console.log('你好' + vari);  // 你好null
console.log(11 + vari);     // 11
console.log(true + vari);   //  1

A declared variable is given null value, and the value stored in it is empty. When learning objects, we continue to study null

3.1 Get the data type of the detected variable

typeof can be used to obtain the data type of the
detected variable typeof can be used to obtain the data type of the detected variable

var num = 18;
console.log(typeof num) // 结果 number      

var num=18
console.log(typedef num)
return values ​​of different types
insert image description here
Number typedef 18
Boolea typedef true
typedef null object
typedef null object
3.2 Literals
Literals are the notation of a fixed value in the source code, which is generally a literal Quantity means how to express this value
Literal means how to express this value
Literal means the notation of a fixed value in the source code.
Number literals: 8, 9, 10
String literals: 'dark horse programmer', "big front end"
Boolean literals: true, false

4.1 What is data type conversion

The data obtained by using the form and prompt is of the string type by default. At this time, the addition operation cannot be performed directly and simply, and the data type of the variable needs to be converted. In layman's terms, it is to convert a variable of one data type to another data type.
We usually implement three types of conversions:
conversion to string type
, conversion to numeric type,
conversion to boolean type,
using the form, the data obtained by prompt is string type by default, and
converted to string type, numeric type, and boolean type
4.2 Convert to string
insert image description here
toString(), String(num); Plus sign splicing strings and strings criticize your sister's results are strings, var num=1;alert(num+"I am a string");
toString() Unlike String() usage.
Three conversion methods, we prefer to use the third plus sign concatenated string conversion method, which is also called implicit conversion.
4.3 Convert to numeric type (emphasis)
insert image description here
js implicit conversion-*/
Use arithmetic operation to implicitly convert to numeric type,
pay attention to the capitalization of the words parseInt and parseFloat, these two are the key.
Implicit conversion is when we perform arithmetic operations , JS automatically converts the data type
Implicit conversion is when we perform arithmetic operations, JS automatically converts it into a data type
Case 1: Calculate age
This case requires an input box to pop up on the page. After we enter the year of birth, we can calculate out of our age.
insert image description here
Case study
An input box (prompt) pops up, allowing the user to enter the year of birth (user input)
Save the value entered by the user in a variable, and then subtract the variable value from the year of this year. The result is the current age (internal processing of the program). An
alert box (alert) will pop up, and the calculation result will be output (output result)

// 1. 弹出输入框,输入出生年份,并存储在变量中  
var year = prompt('请输入您的出生年份:');  // 用户输入
// 2. 用今年减去刚才输入的年份   
var result = 2019 - year;               // 程序内部处理
// 3. 弹出提示框  
alert('您的年龄是:' + result + '岁');     // 输出结果

Case 2: Simple Adder

Calculate the value of two numbers, after the user enters the first value, continue to pop up the second input box and input the second value, and finally display the result of adding the two input values ​​through the pop-up window.
insert image description here
First, the first input box pops up, prompting the user to enter the first value and save it,
and then the second box pops up, prompting the user to enter the second value, save it
, add the two values, and assign the result to a new variable ( Pay attention to the data type conversion)
pop up an alert box (alert), and output the result of the calculation (output result)

// 1. 先弹出第一个输入框,提示用户输入第一个值 
 var num1 = prompt('请输入第一个值:');
// 2. 再弹出第二个框,提示用户输入第二个值 
 var num2 = prompt('请输入第二个值:');
// 3. 将输入的值转换为数字型后,把这两个值相加,并将结果赋给新的变量  
 var result = parseFloat(num1) + parseFloat(num2);
// 4. 弹出结果
 alert('结果是:' + result);

var result=parseFloat(num1)+parseFloat(num2);
4.4 Convert to Boolean
insert image description here
Boolean('true')
"",0,NaN,null,undefined,"",0,NaN,nunll,undefined
represents empty, negative The value will be converted to false, such as '', 0, NaN, null, undefined
and the rest of the values ​​will be converted to true

console.log(Boolean('')); // false
console.log(Boolean(0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean('小白')); // true
console.log(Boolean(12)); // true

Guess you like

Origin blog.csdn.net/weixin_43428283/article/details/124077039