当前位置:网站首页>JS foundation -- data type
JS foundation -- data type
2022-07-01 10:48:00 【AsiaFT.】
JS Basics -- data type
- JS Introduce
- JS Three major components
- JS Variable
- 1. Four ways to define variables
- 2. JS Naming specification
- 3. JS data type
- 1. Basic data type
- 2. Reference data type
- 3. Determine whether it is a value
- 4. Convert non numeric type to numeric
- 5. String type
- 6. Boolean value
- 7. null and undefined
- 8. Reference type -- Common object types
- 9. Reference data type -- Array
- 10. The underlying operating mechanism of basic data types and reference data types is different
- 11. Data type judgment
JS Introduce
JS As client language , Interface elements can be operated , You can also manipulate browser behavior .
JS Three major components
JS It's made up of three parts :
ES+DOM+BOM
among ,ES: Defined JS Basic syntax ;
DOM Text object model : You can operate web interface elements ;
BOM Browser object model : You can operate the browser ;
JS Variable
1. Four ways to define variables
1)ES3: var a=10;
2)ES6:
let b=10;
const c=20; # Constant , Can't change
var a=10;
undefined
a=15;
15
let b =1;
undefined
b=12;
12
const c = 23;
undefined
c=24; # If forced assignment to constant , The error is as follows
VM225:1 Uncaught TypeError: Assignment to constant variable.
at <anonymous>:1:2
3) Create a class :
class A {}
4) The import module :
import B from ‘./B.js’
5)Symbol: Define unique values
Usage method :
let Variable name = Symbol( value );
Usually , The value type comparison size compares the value pointed to by the variable . add Symbol It means only , Even if the value is the same , The two variables are also unequal .
var a =10;
> undefined
var b = 10;
> undefined
a==b
> true
let c = Symbol(10)
> undefined
let d = Symbol(10)
> undefined
c==d
> false
2. JS Naming specification
- JS It's case sensitive language .
- Name the constituent elements : Numbers 、 Letter 、 Underline 、$, It cannot start with a number . Because the representation of octal and hexadecimal is 0o and 0x, To make a difference , Cannot start with a number . The variable name and value cannot be the same .
The variable name cannot be the same as the variable value
var hello = hello;
undefined
hello
undefined
Cannot start with a number
var 0o10
# VM911:1 Uncaught SyntaxError: Unexpected number
We can use $ start , Usually used for JQuery Element acquisition
var $q=10
> undefined
$q
> 10
We can use _ start , Usually used to define global variables
var _e=1
> undefined
_e
> 1
3. JS data type
1. Basic data type
- Numerical type number: Numbers +NaN
- Character string: Single quotation marks 、 Double quotes 、 Reverse apostrophe (``) Everything wrapped
- Boolean type boolean
- Null object pointer null
- Undefined undefined
2. Reference data type
- Object data type object
1) {} Common object
2) [] Array objects
3)/^$/ Regular expressions
4) Math Mathematical function object
5) Date object - Function data type function
3. Determine whether it is a value
JS Determine whether it is non numeric use isNaN(), Is non numeric , return true; It's numerical , return false. The method call mechanism : First call the contents in brackets Number() convert , After the transformation , Then judge whether it is a number .
example :
isNaN("12")
false //Number("12")->12
isNaN("true")
true //Number("true")->NaN
isNaN(true)
false//Number(true)->1
isNaN(null)
false//Number(null)->0
isNaN(undefined)
true//Number(undefined)->NaN; isNaN(NaN)->true
4. Convert non numeric type to numeric
- Number([val]): hold Reference type When converting to numbers , Based on **toString()** Method to string , And then convert it to numbers .
Number('true')
NaN
Number(true)
1
Number('')
0
Number(null)
0
Number(undefined)
NaN
Number({
})
NaN//{}.toString()-->({}).toString()-->'[object Object]'-->NaN
Number([])
0//[].toString()-->''
Number([12])
12//[12].toString-->12
Number([12,23])
NaN//[12,23].toString-->'12,23'
- parseInt([val],[ Base number ]): about character string Come on , Search for valid numeric characters from left to right , Until you encounter a non valid numeric character , Stop searching ( No matter whether there are numbers after it , No longer search ). Return what you find as a number . And Number Different ,Number It's the underlying mechanism ,parseInt Is the method
parseInt("12px")
12
parseInt("width:12px")
NaN
parseInt("12px,24px")
12
parseInt() If the value in is not a string , Will be converted to a string first , Find the number again .
Number(true)
1// The underlying mechanism stipulates Number encounter true, Then return to 1
parseInt(true)
NaN//parseInt Encountered non string , First convert it to a string ,true-》'true', And then find 'true' No numbers found in , So back NaN
- parseFloat(): Convert to floating point number
parseFloat("12.5px")
12.5
- == : Converting other types of values to numbers may occur
1=='1'
true
0=='0'
true
0==false
true
1=='true'
false
- Subtraction, multiplication and division :
var a = '12'
undefined
a - '2'
10 // First the '2' call Number() To 2, Then do subtraction .
5. String type
1. toString()
Other data types are converted to strings , By calling .toString(), After calling , Put a pair of quotation marks directly outside the content ( Except for ordinary objects )
- Numerical type :
Can't be used directly Numbers .toString() , Will report a mistake :Uncaught SyntaxError: Invalid or unexpected token
12.toString()
> VM94:1 Uncaught SyntaxError: Invalid or unexpected token
var a=12;
undefined
a.toString()
> '12'
- Boolean type : Boolean value is covered with a layer ’’
true.toString()
> 'true'
- NaN:
NaN.toString()
'NaN'
- null and undefined: No, toString() Method
null.toString()
> VM280:1 Uncaught TypeError: Cannot read properties of null (reading 'toString')
at <anonymous>:1:6
(anonymous) @ VM280:1
undefined.toString()
> VM318:1 Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
at <anonymous>:1:11
- Array :
[].toString()
''
[12].toString()
'12'
[12,23].toString()
'12,23'
[12,23,null].toString()
'12,23,'
[12,23,undefined].toString()
'12,23,'
- Regular :
/^$/.toString()
'/^$/'
- Common object : {}
Common object toString() Not used to convert to string , It is used to obtain data types
({
}).toString()
'[object Object]'
2. +
“+ ” When encountering numbers , That is, numerical operation addition ; When a string is encountered , That is string splicing
In the four operators , Only “+” There is ambiguity , We need to pay attention to , The other three operators are numerical operations , You need to convert the objects at both ends into numerical values .
'12' + 10
> '1210'
'12' - 10
> 2 // The minus sign has no function of character splicing , So you need to put the string '12' call Number() To 12, Then subtract
'12px'*10
> NaN // Conversion will only call Number() , Not invoke parseInt() or parseFloat()
'12'/10
> 1.2
true *10
> 10
[12] * 10
> 120
- Interview questions test
ask :let a = 10 + null + true + [] + undefined + ‘ bead ’+ null + [] +10 + false;
Analysis : Examine the plus sign when encountering numeric values and strings
10 + null : null call Number() Turn into 0, 10 + null become 10
10 + true : true call Number() Turn into 1, 10 + 1 become 11
11+ [] : [] Is a reference type , call Number() On conversion , First call toString() become "", At this time, the plus sign Make a splice , 11 + [] become “11”
11 + undefined + ‘ bead ’ + null + [] +10 + false : “11undefined bead null10false”
let a = 10 + null + true + [] + undefined + ' bead ' + null + [] +10 + false;
undefined
a
'11undefined bead null10false'
If other operators are encountered during the conversion , Then continue with the conversion , There is no splicing
let b = 10 +true -[]
undefined
b
11// [] call toString() Into the "", Call again Number() Empty
6. Boolean value
There are only two values : true and false
Other types are converted to Boolean values
Only 0, NaN, “”, null, undefined These five values are converted to false, Others are true, No exceptions .
- Boolean()
Boolean("")
false
Boolean(" ")
true // Only empty strings are false, Spaces are non empty strings
Boolean([])
true // Empty arrays do not belong to five types
Boolean({
})
true // Empty objects do not belong to five types
- !/!!
! Take the opposite ;
!! Take the reverse and take the reverse again , Equal to directly converting the value to bool, amount to Boolean()
!1
false
!!1
true
- conditional
if If it is a simple number or mathematical operation in brackets , Instead of ==/===/!=/>= Then it turns to Boolean
if("1px")
console.log(" ha-ha ") //"1px" by true
VM1843:2 ha-ha
undefined
if("1px"+1)
console.log(" ha-ha ") //"1px"+1 String splicing , become "1px1" by true
VM1854:2 ha-ha
undefined
if("1px"-1)
console.log(" ha-ha ")//- It can only be a minus sign ,"1px" call Number() become NaN,NaN-1 Still NaN, so "1px"-1 by false, There is no output here “ ha-ha ”
undefined
7. null and undefined
null : Anticipate , Does not occupy a space . It is often used when you don't know the value and type of the object at the beginning , Late assignment ;
undefined: unexpected , After defining variables , No assignment , There will be undefined( The browser decides the assignment ).
8. Reference type – Common object types
Common object types are a way to describe objects , It consists of key value pairs ( All objects are key value pairs ). among , Keys can only be numbers or strings , And the key cannot be repeated . Each set of key value pairs is separated by commas .
1. Definition
Use {} Put in the key value pair , Key value pairs are separated by commas
var dog = {
category: "animal",
skill: "bite"
}
undefined
dog
{
category: 'animal', skill: 'bite'}
2. increase
There are two ways to add attributes :
- Object name . Property name : Attribute name is a nonexistent attribute name , Is a new attribute
dog.legs=4
4
dog
{
category: 'animal', skill: 'bite', legs: 4}
- Object name [ Property name ]:
dog['color']='white'
'white'
dog
{
category: 'animal', skill: 'bite', legs: 4, color: 'white'}
Use object name [ Property name ] When the way , If the attribute name is a string , You need to add quotation marks . If the property name is a number , You can only use this method to add , But can't use . To call .
dog[color]='white'
VM2292:1 Uncaught ReferenceError: color is not defined
at <anonymous>:1:5 //color You have to quote
Object name [ Property name ] The attribute name in can be a number
dog[1]=' The small white '
' The small white '
dog
{
1: ' The small white ', category: 'animal', skill: 'bite', legs: 4, color: 'white'}
If the property name is a number , Then you cannot assign or call
dog.2="12kg"
VM2530:1 Uncaught SyntaxError: Unexpected number
If the attribute name does not exist , Then return to undefined. Because unexpectedly , I didn't expect to call .
dog
{
category: 'animal', skill: null, legs: 4, color: 'yellow'}
dog['name']
undefined
3. Delete
There are two types of deletion , One is true deletion , One is false deletion . True deletion is to delete both the attribute name and attribute value , The false deletion only deletes the attribute value .
- True delete
Use delete
dog
{
1: ' The small white ', category: 'animal', skill: 'bite', legs: 4, color: 'white'}
delete dog[1]
true
dog
{
category: 'animal', skill: 'bite', legs: 4, color: 'white'} // dog Object 1 And its corresponding values are deleted
- False deletion
Assign the attribute value corresponding to an attribute name to null
dog
{
category: 'animal', skill: 'bite', legs: 4, color: 'white'}
dog['skill']=null // Assign a property value to null, You can fake delete
null
dog
{
category: 'animal', skill: null, legs: 4, color: 'white'}
4. Change
Assign a direct value to an existing attribute name , You can overwrite the original attribute value .
dog
{
category: 'animal', skill: null, legs: 4, color: 'white'}
dog['color']='black'
'black'
dog
{
category: 'animal', skill: null, legs: 4, color: 'black'} // take color The original attribute value is changed to black
It's the same as new , There are two ways to call properties :
dog.color='yellow' // Use the point call method , Change the value , Only the attribute name is string , The value cannot be
'yellow'
dog
{
category: 'animal', skill: null, legs: 4, color: 'yellow'}
5. check
Object name . Property name : Only for attribute names that are strings
Object name [ Property name ]: For attribute names that are strings or numbers
9. Reference data type – Array
Array is a special object , So it also consists of key value pairs , But it's special in , Keys are generated by default , There is no need to define it manually , What we write in brackets is the value . The data types of values in the same array can be different .
let arr1=[12,true," The small white ",{
}]
undefined
arr1
(4) [12, true, ' The small white ', {
…}]
0: 12
1: true
2: " The small white "
3: {
}
length: 4 // Arrays have a default property called length, So when we call the array length , You can write directly arr1.length or arr1['length']
[[Prototype]]: Array(0)
10. The underlying operating mechanism of basic data types and reference data types is different
The basic data type is to operate on values , The reference data type is to operate on the address of heap memory
Stack memory function : 1. Store basic type variables and values ;2. Execute code
let a = 12;
let b = a;
b = 13;
console.log(a);
let n = {
name: " The small white "
};
let m = n;
m.name = ' Xiaoxin ';
console.log(n);
The result is :
12
{
name: ' Xiaoxin '}
Operation principle :
- The browser provides space ( Memory )
- The browser provides a main thread to execute code one by one
Exercises 1 :
let n = [10, 20];
let m = n;
let x = m;
m[0] = 100;
x = [30, 40];
x[0] = 200;
m = x;
m[1] = 300;
n[2] = 400;
console.log(n, m, x);
Output results :
[100, 20, 400]
[200, 300]
[200, 300]
Parse the diagram :
Notice here x=[30,40] Is to point to a new array , Need to open up a new heap storage space .
Exercises 2: Ali interview questions 1
let a = {
n: 1
};
let b = a;
a.x = a = {
n: 2 };
console.log(a.x);
console.log(b);
console.log(b.n);
console.log(b.x.n)
Running results :
undefined
{
n: 1,
x: {
n: 2}}
1
2
Exercises 3
let a = {
n: 1 };
let b = a;
a.x = b;
console.log(a.x);
console.log(b);
Execution results
Execute illustration
11. Data type judgment
- typeof [val] Operator
typeof Detected value , Two characteristics :
- It's a string
- The quotation marks contain the corresponding data type ( Console console in , Black represents string , Blue represents numbers )
typeof 1
'number'
typeof NaN
'number'
typeof null
'object'
typeof undefined
'undefined'
typeof "1"
'string'
typeof true
'boolean'
typeof {
}
'object'
typeof []
'object'
typeof /^$/
'object'
typeof Boolean
'function'
typeof shortcoming :
- typeof null : It is detected that object, It's actually a number ;
- typeof object : All detected are object, No further distinction can be made ;
Exercises :
console.log(typeof typeof typeof []);
"string" // typeof []-->"object" , typeof "object"-->"string", typeof "string"-->string
- constructor
- instanceof
- object.prototype.toString.call(): The best way to detect data types
边栏推荐
- The Lantern Festival is held on the fifteenth day of the first month, and the Lantern Festival begins to celebrate the reunion
- 数据库实验报告(一)
- 基金管理人的内部控制
- 网站源码整站下载 网站模板源代码下载
- [MPC] ② quadprog solves positive definite, semi positive definite and negative definite quadratic programming
- Detailed explanation of linear regression in machine learning
- 数据库实验报告(二)
- Daily mathematics serial 55: February 24
- SQL Server列一相同的情况下,如何取列二的最大值,并重新生成表
- JS基础--数据类型
猜你喜欢
Error: missing revert data in call exception
个人商城二开逍遥B2C商城系统源码-可商用版/拼团拼购优惠折扣秒杀源码
106. construct binary tree from middle order and post order traversal sequence
Uncover the secrets of new products! Yadi Guanneng 3 multi product matrix to meet the travel needs of global users
零基础入门测试该学什么?最全整理,照着学就对了
The Lantern Festival is held on the fifteenth day of the first month, and the Lantern Festival begins to celebrate the reunion
移动硬盘驱动器读到,但不显示盘符
Addition, deletion, modification and query of database
商城小程序源码开源版-可二开
CRC verification
随机推荐
机器学习之线性回归详解
缺少比较器,运放来救场!(运放当做比较器电路记录)
Programmers want to go to state-owned enterprises? The technology is backward and the salary is low. I can't find a job after lying flat for several years
[.net6] use ml.net+onnx pre training model to liven the classic "Huaqiang buys melons" in station B
想请教一下,我在广州,到哪里开户比较好?现在网上开户安全么?
Wireshark TS | 快速重传和乱序之混淆
毕业季·进击的技术er
LeetCode 438. Find all letter ectopic words in the string__ sliding window
Handling distributed transactions with powerful dbpack (PHP tutorial)
106. 从中序与后序遍历序列构造二叉树
数据库的增删改查问题
Prefabricated dishes usher in the "golden age", who can lead the next trillion market
Valgrind usage of memory leak locating tool
CCNP Part XII BGP (IV)
12.Gateway新一代网关
零基础入行软件测试必看,10年测试老鸟的良心建议(共15条)
Database experiment report (I)
[encounter Django] - (II) database configuration
[MPC] ② quadprog solves positive definite, semi positive definite and negative definite quadratic programming
CodeBlocks 左侧项目栏消失,workspace 自动保存项目,Default workspace,打开上次的workspace,工作区(图文教程,已解决)