Focus on the basic knowledge of JS

Everything_ is_ none 2021-05-04 13:58:32
focus basic knowledge js


A preliminary understanding JaveSctript

  • Web The composition of the standard
title Content explain
structure HTML The structure and content of web page elements
performance CSS The appearance and location of web page elements , Including layout and color 、 size
Behavior js The definition and interaction of web model
  • Javascript Is a programming language , Can be used to create dynamically updated content , Control multimedia , Making image animation and so on to achieve human-computer interaction effect , Simply speaking , You can use short code to achieve magical functions .
  • JavaScript The way of writing , The norm is script The label is written in body above
    • inline JavaScript
    • Inside JavaScript
    • external JavaScript
  • Terminator
    • Represents the end of a statement , In English ; Express .
    • Write but not write .
    • A newline ( enter ) Will be recognized as a Terminator , Therefore, in the actual development, many people advocate writing JavaScript Code , Omit the Terminator .
    • But to unify the style , To finish, write every sentence , Or you don't write every sentence .
  • JavaScript I / O statement
    • Output and access can be understood as the interaction between human and computer , The user uses the keyboard 、 The mouse, etc. inputs information to the computer , The computer processes it and shows it to the user , This is a process of input and output .
    • Output statement
      • ducoment.write(" What to output ")
        • towards body Output content inside
        • If the output is a label , It will also be parsed into web page elements
      • alert( What to output )
        • Page pop-up , Output the corresponding content
      • console.log( What to output )
        • The console outputs the corresponding content , Usually help us debug .
    • Input statement
      • prompt(" Please enter your name ")

Variable

  • The goal is : Understand that variables are the basis for computers to store data Containers , To master the variables Declaration method

What is a variable

  • vernacular : A variable is a box .
  • popular : Variables are the containers in which computers store data , It allows computers to remember .

Basic use of variables

How variables are declared

  • You want to use variables , First, create variables ( It's called declaring variables )
  • There are two parts to declaring variables : Declare keywords 、 Variable name ( identification )
  • let That is the keyword ,let( allow 、 The license 、 Give Way 、 want ), The so-called keyword is a special declaration provided by the system ( Definition ) Variable words
  • let grammar
    //let Declare a variable , for example 
    let age
    //let Declare variables and assign values 
    let age = 18
    //let Declare multiple variables at the same time and declare 
    let age = 18, name = " Zhang San "
     Copy code 
  • Use let What should we pay attention to when doing this
    • Allow declaration and assignment to happen at the same time .
    • Duplicate statements are not allowed
    • JavaScript Some built-in keywords in can't be used as variable names
    • Multiple variables can be declared and assigned at the same time
  • Variable assignment
    • After defining a variable , You can initialize it ( assignment ), After the variable name, add a = Number , And then follow the numbers
    • grammar
    let age
    age = 18
     Copy code 
  • Update variables
    • After variable assignment , You can also give it a different value to update it .
    • grammar
    let age
    age = 18
    age = 19
     Copy code 
    • Be careful
      • let Can be reassigned, but cannot be defined repeatedly ( Statement )

The nature of variables

  • Memory : A place in a computer where data is stored , It's like a space .
  • Variable : It's a small space that the program applies for in memory to store data .

Variable naming rules and specifications

The rules : Must abide by the , Failure to comply will lead to mistakes

  • Cannot use keyword .
    • keyword : Characters with special meanings ,JavaScript Some built-in English words . for example :let var if for wait .
  • Only underline 、 Letter 、 Numbers 、$ form , And the number can't start .
  • Letters are strictly case sensitive , Such as Age and age It's a different variable .

standard : Suggest , Failure to comply will not result in an error , But not in line with the general knowledge of the industry

  • The name should be meaningful .
  • Obey hump naming
    • The first character of the first word is lowercase , After that, each word is capitalized . for example userName

data type

  • Everything in the computer world is data .
  • A computer program can process a lot of data , In order to facilitate data management ( Different uses ), Divide the data into different types
data type effect Representation form example
String( character string ) Represents the content of the text Single or double quotation marks in English 'hello'、“world”
Number( Numbers ) Represents digital content Write numbers directly 10,20
Boolean( Boolean ) Two states of opposition , True or false , Right or wrong and so on true and false ture、false
undefined( Undefined ) Means undefined undefined undefined
Object( object ) Represents a common object Key value pairs wrapped in braces {name:nihao}
Null( Null value ) Represents an empty object null null
Array( Array ) Represents an array object Wrap it in brackets [1,2,3]
Regex( Regular ) Express regular objects Wrap it in a backslash /^[+-]?/

Numeric type (Number)

  • The numbers we learn in math , It can be an integer 、 decimal 、 Positive numbers 、 negative 、NaN( The digital ).

NaN

  • NaN:not a number; It means a number , But it's a number type .
  • NaN It's not equal to any value , Including myself .

isNaN()

  • Detect whether a value is a significant number , If it's not a significant number, return true, If it's a significant number, return false.
  • Reuse isNaN This method , First, it detects whether the detection value is a number , If not , It's implicitly transformed , use Number() This method first converts the value to a numeric type and then detects it .

Number() conversion

  • Convert string to number , As long as the string contains any invalid numeric character, the result is NAN, An empty string returns 0
  • Convert the reference data type to a number , It's based on toString() Method to string

pareseInt() and parseFloat()

  • parseInt() Convert other data into numeric integers
  • parseFloat() Turn other data into numbers , Take the decimal point .
var a = '12px'
console.log(parseInt(a))//12
let ary = [13,14]
console.log(parseInt(ary))//13
// It converts other data types first to string types ,ary.toString() The return value is '13,14'.
 Copy code 

String type (String)

  • Through single quotes ''、 Double quotes "" Or back quotes `` Package data is called string , There is essentially no difference between single quotation marks and double quotation marks , Single quotation marks are recommended .
  • A string is made up of zero to multiple characters , Each character has its own index of position , By a length Store the length of the string .
  • Be careful
    • Both single quotation marks and double quotation marks must be used in pairs
    • Single quotation marks / Double quotation marks can be nested inside each other , But you can't nest yourself , Double outside and single inside or single outside and double inside are OK .
    • Escape characters can be used if necessary \ Output single or double quotes

String splicing

ES6 New template string

  • ${} Where is the js expression , It can be variables and variable operations , Ternary operators and so on .
var x = 15
console.log(`${x}px`)//15px
let b = 3
console.log(`${x*b}px`)//45px
 Copy code 

utilize + Splicing

  • + There is a string on either side of the number , The result is string splicing
  • + There is an object on the left and right sides of the number ( The goal is to turn objects into numbers , Do math )
    • The system first gets the object's [Synbol.toPrimitive] Property value
    • If you don't have this property , Second, get his valueOf(); The original values are all basic data types .
    • If there is no original value yet , Finally, it will be converted to a string toString, It turns out to be string splicing .
let a = 46
console.log(a+' year ')//46 year 
let ary = [12,13]
ary[Symbol.toPrimitive]//undefined
ary.valueOf()//[12,13] // This is not his original value , All raw values are basic data types 
let num = new Number(10)// This is an object 
console.log(num[Symbol.toPrimitive],num.valueOf) //undefined 10
console.log(num+10) //20
 Copy code 
  • + The number is only on one side , So this side is even strings / object , It's also a number operation

String method

Get the characters in the string

  • Using variables [] You can get
  • utilize charAt() Method
let str = 'fhcsj'
console.log(str[2])//c
console.log(str[str.legnth-1])//j
console.log(str.charAt(2))//c
 Copy code 

Convert other data types to string types

  • utilize Variable .toString() Method
  • utilize String( Variable )
  • Be careful :
    • Array to character to , The return value is to separate each item in the array with a comma
    • For ordinary objects, convert to strings , No matter what value is contained in the object , The final return value is "[object Object]"
let num = 15,
ary = [11,13]
num.toString()//'15'
String(num)//'15'
ary.toString()//'11,13'
let obj = {}
obj.toString()//"[object Object]"
 Copy code 

charCodeAt()

  • Returns the encoding of the index corresponding to the string

substr(start,end)

  • String interception

slice(start,end)

  • Returns a new string , Interception from start The index to the end, But not including end Indexes .

split(separator,howmany)

  • Use the specified separator( must ) Parameters , Split a string into arrays ,howmany( Optional ) Define the length of the array , If you don't write howmany Parameters , There is no limit on the length of the array .
    let str = 'fdkfhkds'
    console.log(str.split('k'))//[fd,fh,ds]
    console.log(str.split('k',2))//[fd,fh]
     Copy code 

replace(regexp/substr,replacement)

  • use (replacement character ) Replace In the string (substr character ) Or replace a character that matches the regular .
    let str = 'fsfsdhfsdfs'
    console.log(str.replace('fs','i'))//ifsdhfsdfs, It will only replace the first 
    console.log(str.replace(/fs/),i)//ifsdhfsdfs, Writing it like this will only replace the first 
    console.log(str.replace(/fs/g),i)//iidhidi, To write like this is to replace all... In the string fs
     Copy code 

indexOf(searchValue,fromIndex)/lastIndexOf(searchValue,fromIndex)

  • indexOf()
    • Returns the string value specified for retrieval (searchValue, Must write ) The index of ,fromIndex( Specify which index value to start with , Optional )
    • If the specified string value is not retrieved in the string , Will return -1.
  • lastIndexOf()
    • Returns the index of the first occurrence of the specified string value from right to left ,fromIndex What character does the rule start with ( This character is counted from the back to the front ). Be careful : its 0 The index is also the first character on the left .
    • If the specified character value cannot be retrieved from the string, return -1
let str = 'fsdhkhds'
console.log(str.indexOf('d'))//2
console.log(str.indexOf('d',3))//6
console.log(str.lastIndexOf('d'))//6
console.log(str.lastIndexOf('d',2))//2
 Copy code 

includes(searchValue,fromIndex)

  • Determine whether the string contains the specified character value (searchValue), Starting with the prescribed index (fromIndex), The return value is true perhaps false
let str = 'fdsds'
console.log(str.includes('a'))//false
console.log(str.includes('s'))//true
 Copy code 

Boolean type (Boolean)

  • When expressing positive or negative , In the computer, the corresponding is boolean type , It has two fixed values true perhaps false.
  • Two ways to convert other data types to Boolean types
    • Boolean(value)
    • !!value
  • notes : Only 0、NaN、 An empty string 、undefined The value that becomes Boolean is false, Everything else is true.

Undefined type (undefined)

  • Undefined type is a special type , Only one value undefined.
  • What happens to undefined types ?
    • Only declare variables without assignment , The default value of the variable is undefined, Generally, it is rare to assign a value to a variable undefined.

Symbol( Represents a unique value , It's a basic data type )

let a = Symbol(0)
let b = Symbol(0)
console.log(a==b)//false
 Copy code 

Object data type

Common object

  • use {} Wrapped key value pairs represent , An array of class 、 example 、 Prototype object ......

Array objects

  • use [] Wrapped expression

Regular objects

  • use // Wrapped expression

Date object

function Function

  • function : Blocks of code designed to perform specific tasks
  • explain : Functions can wrap code blocks with the same or similar logic , Execute the code logic through function calls , The advantage of this is that it helps to simplify the code , Convenient reuse .
  • grammar
    function Function name () {
    The body of the function
    }
    // Function call , The code logic in the function body is executed 
    Function name ()
    // Repeatable , There is no limit to the number of times .
     Copy code 
    • Naming conventions for functions
      • Basically consistent with variable naming
      • Try to use hump naming
      • The prefix is usually a verb
      • Naming suggestions : Common verb convention .
Common verbs meaning
can Determine whether an action can be performed
has Determine whether to mean a value
is Judge whether it is a certain value
get Get a value
set Set a value
load Load some data

Test data type

typeof

  • grammar let age = 18;console.log(type age)
  • Be careful
    • typeof Can detect basic data types .
    • typeof undefined The return value of undefined.
    • type null The return value of object.

JS Arithmetic operator

  • Mathematical operators are also called operators , It mainly includes fake 、 reduce 、 ride 、 except 、 Remainder ( modulus ).
describe Symbol
Sum up +
Subtraction -
quadrature *
Seeking quotient /
Take the remainder ( modulus ) %
    • Operators are special
      • + Operators are summation operations in numeric types
      • + Operators are splices in string type .

Data type conversion

Implicit conversion

  • When some operators are executed , The data type is automatically converted inside the system , This type is called implicit conversion .
  • The rules
    • + One of the two sides of the number is a string type , Will automatically convert the other to a string .
    • except + All arithmetic operators other than the symbol convert data to numeric types .

Explicit conversion

  • It's not rigorous to rely too much on implicit transformation inside the system when writing programs , It's better to use explicit conversion .
  • Number( data )
    • Turn to number type
    • If there are non numbers in the string content , When the conversion fails, the result is NaN(Not a Number) It's not a number .
    • NaN It's also number Data of type , For non numeric
  • Boolean( data )
    • To Boolean
    • 0、 An empty string 、NaN、undefined、null Turn into false, Everything else is true.
  • Variable .toString()

ES6 Knowledge point

Deconstruct assignment

  • ES6 Deconstruction assignment in , Mainly for objects and arrays , The left side defines a structure similar to the right side value , Declare a few variables like this , Quick access to every part of the information .

Array structure assignment

let arr = [1, 2, 3, 4]
let [x, y] = arr
console.log(x, y)//1, 2
// If you use it below x,y Variable structure assignment , May be an error , say x,y Already exists 
let[y,...x] = arr// Report errors 
//... Represents the residue operator , It means that the rest of the array is taken and put into b in 
let [a,...b] = arr
console.log(a, b)//1, [2, 3, 4]
// The comma stands for each of the preceding items 
let[, , , x, y] = arr
console.log(x, y) // 40 undefined
// You can also give a default value to the variable assigned to the structure , If there is no value, it is equal to the default value 
let [, , , , b = 0] = arr
console.log(b)//0
 Copy code 

Object's deconstruction assignment

// Declared by default " Variable " Need and " Consistent property names ", In this way, the object can get the value of the specified member 
let obj = {
name:' Everest training ',
age:11,
teacher:'fc',
0:100
}
let {name,age} = obj
console.log(name, age) // ' Everest training ' 11
// Make a statement x Variable , And will obj.name Assign a value to x
let {name: x} = obj
// When deconstructing assignment , You can set default values for variables 
let { x = 0 } = obj
// If this property value does not exist , Then the default value is assigned 0
console.log(x)//0
// And the number property name , We can rename a new variable to receive the value 
// If you write it directly, you will report an error , There are two ways to report an error 
let {0} = obj
let {[0]} = obj
// Write it correctly 
let{0: x} = obj
console.log(x)//100
// Get the domain name and address of the website quickly 
let {hostname:domain, pathname:path} = location;
// The combination of array structure assignment and object structure assignment 
let ary = [100,' Hello ',{name: 'hello',score:[12, 13]}]
let [, y, {score:[, math]}]
console.log(y,math)//' Hello ',13
 Copy code 
版权声明
本文为[Everything_ is_ none]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210504135742311l.html

  1. css单位
  2. CSS unit
  3. 前端验证集合
  4. Front end validation collection
  5. Front end learning (4) -- response line, response head, response body
  6. Explain HTTP message in detail
  7. Lesson 27: using time measuring tools to explore available spare time
  8. CSS 单位
  9. CSS unit
  10. 前端工具集合
  11. Front end Tools Collection
  12. Introduction to HTTP message format
  13. Vue入门常用指令
  14. Introduction to new features of HTML5
  15. Common instructions for Vue
  16. Introduction of bootstrap Blazer component library
  17. HTML5 速览
  18. HTML5 quick view
  19. HTML表格自动排序
  20. For less than $1700, create a private cloud with openstack
  21. Basic learning of JavaScript (1)
  22. Front end learning about nginx
  23. Front end interview of HTTP protocol things!
  24. 前端编程之路一一HTML标签分类
  25. Front end Programming: HTML tag classification
  26. ColSpan and rowspan merging cells of HTML form elements
  27. JavaScript 日期时间格式化
  28. JavaScript date time formatting
  29. Classification of front end interview questions - html2
  30. One time nginx proxy_ set_ Analysis and extension of header fault
  31. HTML learning
  32. CSS块元素
  33. CSS block elements
  34. Summary of HTML5 knowledge points (5)
  35. HTML5 form detailed tutorial
  36. HTML5 form detailed tutorial
  37. HTML5新增的元素表
  38. New element table in HTML5
  39. 3D轮播插件vue-carousel-3d非官方最全文档
  40. 3D carousel plug-in vue-carousel-3d
  41. Uniapp (Vue general) integrates Tencent location service SDK -- multi platform small program general
  42. Slowhttptest slow attack tool use details
  43. Xi Da Pu Ben, wechat finally supports the opening of small programs on the Internet!
  44. HTML summary (2)
  45. css3总概
  46. Overview of CSS3
  47. Front end abnormal monitoring system
  48. 免费网站部署和免费数据库Serverless云存储资源汇总整理
  49. Free website deployment and collection of free database serverless cloud storage resources
  50. Vux form -- a form solution of base vux
  51. 可以直接用于HTML中的特殊字符表 unicode字符集
  52. Can be directly used in HTML special character table Unicode character set
  53. Detailed explanation of HTTP protocol
  54. HTTP request header and request response header
  55. CSS background深度解析
  56. Research on front end exception monitoring solution Tencent CDC
  57. Python web/HTML GUI
  58. Front end standard 2: HTML you know and don't know
  59. Some HTML tags
  60. HTML标签之table