Get to know JaveSctript first

  • What constitutes a Web standard
The title content instructions
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 Definition and interaction of web page models
  • Javascript is a programming language that can be used to create dynamically updated content, control multimedia, create images and animations, etc., to achieve human-computer interaction. In short, it can achieve magical functions through short code.
  • The way JavaScript is written,The specification is that the script tag is written above the body
    • Inline JavaScript
    • Internal JavaScript
    • External JavaScript
  • terminator
    • Represents the end of a statement, in English;Said.
    • You can write without writing.
    • The newline character (carriage return) is recognized as the terminator, so in practice many people advocate omiting the terminator when writing JavaScript code.
    • But in order to keep the style consistent, write every sentence or not at all.
  • JavaScript input and output statements
    • Output and output can be understood as the interaction between human and computer. Users input information to the computer through the keyboard and mouse, and the computer processes it and then shows it to the user. This is an input and output process.
    • Output statements
      • Ducoment.write (" What to output ")
        • Output content inside the body
        • If the output is a tag, it will also be parsed as a page element
      • Alert (What to output)
        • A dialog box is displayed
      • Console. log(what to output)
        • The console outputs the corresponding content, which usually helps us debug.
    • The input statement
      • Prompt (" Please enter your name ")

variable

  • Objective: To understand that variables are containers in which computers store data, and to master how variables are declared

What is the variable

  • In plain English: A variable is a box.
  • Popular: a variable is a container in which the computer stores data that the computer can remember.

Basic use of variables

How a variable is declared

  • To use variables, you need to create them (or declare them in the technical parlance)
  • Declaring a variable consists of two parts: declaring a keyword and a variable name (identifier)
  • Let is the keyword, let(permit, permit, permit), the so-called keyword is provided by the system specifically used to declare (define) variables
  • Let the grammar
    //let declares a variable, for example
    let age
    //let declares variables and assigns values
    let age = 18
    //let declares multiple variables simultaneously and declares them simultaneously
    let age = 18The name ="Zhang" 
    Copy the code
  • Considerations when using let
    • Allows simultaneous declaration and assignment.
    • Duplicate declarations are not allowed
    • Some keywords built into JavaScript cannot 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 by adding a = sign to the name of the variable, followed by the value
    • grammar
    let age
    age = 18
    Copy the code
  • To update the variable
    • Once a variable is assigned, it can be updated by giving it a different value.
    • grammar
    let age
    age = 18
    age = 19
    Copy the code
    • Pay attention to
      • Let can be reassigned but cannot be defined repeatedly (declared)

Nature of variables

  • Memory: The place in a computer where data is stored, equivalent to one space.
  • Variable: a small area of memory that a program requests to store data.

Naming rules and conventions for variables

Rules: You must follow them. If you don’t follow them, you’ll make a mistake

  • You cannot use keywords.
    • Keywords: characters with special meanings, some English words built into JavaScript. Let var if for, etc.
  • The value can contain only letters, digits, and underscores (_), and cannot start with a digit.
  • Letters are strictly case sensitive, as Age and Age are different variables.

Specification: suggestion, no error will be reported if not followed, but not in line with industry knowledge

  • Make your name meaningful.
  • Follow the camel’s name
    • The first character of a word should be lowercase and the first letter of each subsequent word should be uppercase. Such as the userName

The data type

  • Everything in the computer world is data.
  • Computer programs can process large amounts of data, which are divided into different types for easier management (for different purposes)
The data type role representation case
String (String) Express text content Enclose single or double quotation marks in English ‘hello’, “the world”
Number = Number Represents digital content Just write the numbers 10, 20
Boolean (Boolean) Two opposing states, true or false, true or false, and so on True and false True, false,
Undefined – undefined Indicates undefined undefined undefined
An Object Represents a common object A key-value pair enclosed in braces {name:nihao}
Null Represents an empty object null null
Array Representing array objects Wrap it in brackets [1, 2, 3]
Regex (regular) Expressing a regular object Wrap it with a backslash / ^ (+ -)? /

Number type

  • The numbers we learn in mathematics can be integers, decimals, positive numbers, negative numbers, NaN (non-numbers).

NaN

  • NaN:not a number; It doesn’t mean a number, but it’s a number type.
  • NaN is not equal to any value, including itself.

isNaN()

  • Checks if a value is a significant digit, returning true if it is not, and false if it is.
  • When the isNaN method is used again, it first checks to see if the value is a number, and if it is not, it implicitly converts it toNumber()This method converts the value to a numeric type and then tests it.

The Number ()

  • Converts a string to a number, as long as the string contains any non-valid numeric characterNAN, the empty string is returned0
  • To convert a reference data type to a number, it is based ontoString()Method to a string

PareseInt () and parseFloat ()

  • ParseInt () converts other data to numeric integers
  • ParseFloat () converts other data to numbers, up to the decimal point.
var a = '12px'
console.log(parseInt(a))/ / 12
let ary = [13.14]
console.log(parseInt(ary))/ / 13
// it converts the other data types to strings first, with ary.tostring () returning '13,14'.
Copy the code

String type (String)

  • By single quotation mark' ', double quotation marks""Or data wrapped in backquotes is called a string. There is no difference between single quotes and double quotes.
  • A string is composed of zero to multiple characters, each character has its own index of position, and a length stores the length of the string.
  • Pay attention to
    • Both single and double quotation marks must be used in pairs
    • Single and double quotation marks can be nested within each other, but not within themselves.
    • Escape characters can be used if necessary\Output single or double quotes

String splicing

New template character string for ES6

  • The ${}Js expressions 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 the code

using+Joining together

  • +Strings appear on either side of the sign, resulting in string concatenation
  • +There is an edge to the left and right of the number to produce an object.
    • The system will get the object first[Synbol.toPrimitive]Attribute values
    • If it does not have this property, then get hisvalueOf(); Primitive values are primitive data types.
    • If you don’t have the original value, you end up converting it to a string toString, which is a string concatenation.
let a = 46
console.log(a+', ')/ / 46 years old

let ary = [12.13]
ary[Symbol.toPrimitive]//undefined
ary.valueOf()//[12,13] // this is not his primitive value, all primitive values are primitive 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 the code
  • +The sign appears on only one side, so that side, even if it is a string/object, is a numeric operation

String methods

Gets the characters in the string

  • Using the variable[]Index fetch
  • usingcharAt()methods
let str = 'fhcsj'
console.log(str[2])//c
console.log(str[str.legnth-1])//j

console.log(str.charAt(2))//c
Copy the code

Convert other data types to string types

  • usingVariables. The toString ()methods
  • usingString (variable)
  • Note:
    • Array to character, the return value is to separate each item in the array with a comma
    • For a normal object converted to a string, the final return value is no matter what value the object contains, right"[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 the code

charCodeAt()

  • Returns the encoding of the index corresponding to the string

substr(start,end)

  • String interception

slice(start,end)

  • Returns a new string truncated from the start index to end, but not the end index.

split(separator,howmany)

  • Separator Splits the string into arrays using the specified separator (required) argument. Howmany (optional) defines the length of the array. If no howmany argument is written, there is no limit to 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 the code

replace(regexp/substr,replacement)

  • Replaces (substr character) in a string with (replacement character) or a character that matches the re.
    let str = 'fsfsdhfsdfs'
    console.log(str.replace('fs'.'i'))//ifsdhfsdfs, which replaces only the first one
    
    console.log(str.replace(/fs/),i)//ifsdhfsdfs, so it will only replace the first one
    
    console.log(str.replace(/fs/g),i)//iidhidi replaces all fs in the string
    
    Copy the code

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

  • indexOf()
    • Returns the index of the specified string value (searchValue, mandatory) to be retrieved, fromIndex(optional, which index value to start retrieval from)
    • If the specified string value is not retrieved in the string, -1 is returned.
  • lastIndexOf()
    • Returns the index from right to left of the first occurrence of the string value specified for retrieval, fromIndex specifies the number of characters to begin with (where the character is counted backwards). Note: its 0 index is still the first character on the left.
    • Returns -1 if no specified character value is retrieved from the string
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 the code

includes(searchValue,fromIndex)

  • Determines whether the string contains the specified character value (searchValue), starting with the specified index (fromIndex), and returning true or false
let str = 'fdsds'
console.log(str.includes('a'))//false
console.log(str.includes('s'))//true
Copy the code

Boolean type (Boolean)

  • The computer equivalent for affirmative or negative is a Boolean, which has two fixed values, true or false.
  • Two ways to convert other data types to Boolean types
    • Boolean(value)
    • !!!!! value
  • Note: only 0, NaN, empty string, undefined to Boolean values are false, the rest are true.

Undefined type (undefined)

  • An undefined type is a special type that has only one value, undefined.
  • When does an undefined type occur?
    • If a variable is declared only and no value is assigned, the default value of the variable is undefined. It is rare to assign undefined to a variable.

Symbol (unique value, basic data type)

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

Object data type

Ordinary objects

  • with{}Wrapped key-value pair representation, class array, instance, prototype object……

The array object

  • with[]Wrapped in said

Regular object

  • with//Wrapped in said

The date object

Function is the Function

  • Function: A block of code designed to perform a specific task
  • Description: functions can wrap code blocks with the same or similar logic, and execute these code logic through function calls. The advantage of doing this is to simplify code and facilitate reuse.
  • grammar
    functionThe function name () {function body}// function call, the code logic inside the function is executedThe function name ()// Can be repeated, the number of times is unlimited.
    Copy the code
    • Naming conventions for functions
      • Basically the same as variable names
      • Try to use camel name
      • Prefixes are usually verbs
      • Naming suggestions: Common verb conventions.
Common verbs meaning
can Determines whether an action can be performed
has Determines whether a value is defined
is Determines whether it is a value
get Get a value
set Set a value
load Load some data

Detection data type

typeof

  • grammarlet age = 18; console.log(type age)
  • Pay attention to
    • Typeof can detect basic data types.
    • typeof undefinedReturns undefined.
    • type nullIs an object.

JS arithmetic operator

  • Mathematical operators are also called operators, including false, subtraction, multiplication, division, and mod.
describe symbol
sum +
Strives for the poor
quadrature *
O, /
Take the remainder (modulus) %
    • Operators are special
      • The + operator is the sum operation in numbers
      • The + operator is concatenated in strings.

Data type conversion

Implicit conversion

  • When certain operators are executed, the system automatically converts data types. This type is called implicit conversion.
  • The rules
    • If either side of the + sign is a string, the other is automatically converted to a string.
    • All arithmetic operators except the + sign convert data to numeric type.

Explicit conversion

  • It is not prudent to write programs that rely too much on implicit conversions within the system; it is better to write programs that rely too much on explicit conversions.
  • Number (data)
    • To a numeric type
    • If the string contains non-numbers, the conversion fails and the result is NaN(Not a Number), which is Not a Number.
    • NaN is also data of type number, representing non-numbers
  • Boolean (data)
    • To a Boolean type
    • 0, empty string, NaN, undefined, null are converted to false, and all others are true.
  • Variables. The toString ()

ES6 knowledge

Deconstruction assignment

  • In ES6, deconstruction assignment is mainly for objects and arrays. The left side defines a structure similar to the right side values. In this way, several variables are declared and information about each part is quickly obtained.

Array structure assignment

let arr = [1.2.3.4]
let [x, y] = arr
console.log(x, y)/ / 1. 2

// If x, y is already present, it will be reported as x, y already exists
let[y,...x] = arr/ / an error

/ /... Stands for residual operator, which means the rest of the array is taken and put into B
let [a,...b] = arr
console.log(a, b)/ / 1, 2, 3, 4]

// The comma represents each of the preceding items
let[, , , x, y] = arr
console.log(x, y) // 40 undefined

// It is also possible to assign a default value to the variable assigned to the structure. If there is no value, it equals the default value
let [, , , , b = 0] = arr
console.log(b)/ / 0
Copy the code

Object destructuring assignment

// By default, the declared "variable" needs to be the same as the "attribute name" so that 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

// Declare an x variable and assign obj.name to x
let {name: x} = obj

// When destructing assignments, variables can be set to default values
let { x = 0 } = obj
// If no such attribute value exists, the default value 0 is assigned
console.log(x)/ / 0

// For numeric attribute names, we rename a new variable to receive the value
// If you write directly, you will get an error
let {0} = obj
let {[0]} = obj
// Write it correctly
let{0: x} = obj
console.log(x)/ / 100

// Get the domain name and url of the website quickly
let {hostname:domain, pathname:path} = location;

// A combination of array and object structure assignments
let ary  = [100.'hello', {name: 'hello'.score: [12.13]}]
let [, y, {score:[, math]}]
console.log(y,math)/ / 'hello', 13
Copy the code