JavaScript basics (1)

JavaScript (basic part)

Introduction to JS

  • JS is a lightweight scripting language, an embedded language that provides few algorithms. Script language does not have the ability to develop operating systems and can only be used to write and control other large applications.++
  • The running environment in which JS can control browser web pages is the browser
  • JS has a wide range of applications. It can write both front-end and back-end ( Nodejs), as well as small programs and apps.
  • JavaScriptRelationship with ECMAScript: ES is a specification of JS, and JS is an implementation of ES. In daily situations, the two are interchangeable.

JS statements, identifiers, variables

statement

  • It is recommended that JS statements end with a semicolon, which is used in HTML

identifier

  • An identifier is a legal name used to identify various values . The most common identifier is the variable name.
  • In JS, in addition to letters, numbers, underscores, and numbers that do not start with numbers, the dollar sign $ and Chinese characters are also added as legal identifiers:: It is not recommended to use Chinese characters as variable names::
  • This is the same as Python

variable

  • var num=10;Declare a variable, var is the keyword
  • Printing: console.log(变量名)It cannot be seen in the html web page. You need to check → the console to see the printed variables.
  • 变量提升(hoisting): The way the JS engine works is to first parse the code, obtain all declared variables, and then run it line by line . This causes all statements that declare variables to be promoted to the head of the code, which is called variable promotion!
  • Notice! The variable promotion here is equivalent to before the statement var name;, that is, the variable is declared in advance but the variable is not initialized. The variable initialization is implemented after the subsequent execution of the statement . If the variable is printed before the variable is initialized, then it will display undefinedtype

JS introduces files, comments, and common output methods

Import files

  • JS, like CSS, needs to be introduced into the HTML file to run
  • three methods
    • Embed into HTML file:<body><script>...</script></body>
    • Introduce local independent JS files:
      • Write all JS code to a separate file. This file is called a JS file and ends with .js
      • Then <body>add it in <script>, add srcthe import resource attribute, and introduce the file through the path of the input file (not a link, it is connected through attributes) ++ Of course, you can also write it in , but it is strongly recommended to write it in ++
    • Import files from network sources
      • JS has many functions that others have already written, and we can directly introduce them into our own projects. ++We will come into contact with the jQuery class library later, which can better help us operate JS++
      • Find the target js file, which is full of code written by others. Our import method is the same as the local JS file, that is, the address is changed into a network address.

Note: There are single lines and multiple lines, consistent with C

%% Damn it! The shortcut key for comments is ctrl+/

output method

  • Popup window output:
    • A dialog box pops up in the browser to display the content to be output. alert first converts the content to be output into a string and then outputs it alert("内容")(all executed in the JS file)
    • ++This pop-up box is the same one that reminds me that the password level is too low when I access the Wuli Academic Affairs System. It is also the same one that the browser uses to restore the previous page. It is exactly the same. It was originally written in JS++
  • Write to the page: document.write("内容"), the content is on the page
  • Print/console output: console.log(变量名)It cannot be seen in the html web page. You need to check → the console to see the printed variables++ This method is used the most++

type of data

  • ES5 has a total of 6 data types, including number, string, boolean, object, null, and undefined (questions often examined in interviews!!!) ES6 adds Symbolthe and BigInttype
  • Classification:
    • Primitive/basic data types: numeric, string, boolean. ::String types can be wrapped in single quotes or double quotes::
    • Reference/synthetic data type: Object. An object is often composed of multiple primitive types of values. An object can be regarded as a container that stores various values. It is a bit like JSON ++. The difference between JSON and JSON is that the key in the key-value pair of the object is not String, the left key in JSON must be string++
    • Special values: null and undefined both represent empty. The grammatical effects and meanings are almost the same, but there are historical reasons for dividing them into two. Null generally represents that the object is empty, and undified generally represents that the numerical variable is empty.
  • Numeric value (Number type)
    • Divided into integers and floating point numbers, the number represented by Number has a range. If it exceeds this range, ±Infinity will be returned.
    • Special numbers:
      • Positive infinity: Infinity
      • Negative infinity: -Infinity
      • NaN:Illegal number ::Not a Number::
  • Undefined
    • The Undefined type has only one value, that is, undefinedwhen a variable is declared using var but not initialized , the value of this variable is undefined.
  • Null
    • The undefined value is actually derived from the null value , so if you compare undefined and null to see if they are equal, true will be returned.

Note: Semantically, null represents an empty object, so using typeof to check for null will return an Object.

  • cast
    • stringtoString()/String()/拼串

operator

typeof operator

The %% typeof operator can detect data types (determine basic data types)

  • console.log(typeof var);
    • Can be returned according to different data typesnumber/string/boolean/object
    • Our judgment of the object is not accurate because many other types are also returned object, so we use typeof to judge three basic data types.

comparison operator

  • There are new operators ===and · !==!!!
  • ==What is judged is whether the two values ​​are equal, not whether the two values ​​belong to the same data type. ===It is a strict equality symbol to determine whether it is completely equal . For example, we have two data 10 and "10". The values ​​of these two data are exactly the same, both are 10. If they are equal, true will be returned. However, ===it will be judged that the data types of the two numbers are different, and false++ will be returned.
  • The same !==is true for the strict inequality operator

Boolean operators: negation!, and&&, or ||

  • For negating non-Boolean values , the negation operator will first convert it to a Boolean value and then negate it! What is printed are true and false , not 1 and 0
  • There are only six values ​​in total that are true when inverted:undefined/null/false/0/NaN/空字符串

string

symbol

  • A string is zero or more characters placed together in single or double quotes. Double quotes can be used inside a single-quoted string. Inside a double-quoted string, single quotes can be used
  • If you want to use single quotes inside a single-quoted string, you must add a backslash before the inner single quotes to escape them . The same goes for double-quoted strings that use double quotes internally. ++Because if two single quotes or double quotes are used at the same time, the first two form a pair, and the last two form a pair, the content in the middle will be shelved and an error will be reported++
  • for example 'Did she say \'Hell0\'?', "Did she say \"Hello\"?". But this is not very readable, so it is recommended to use single and double quotes together.
  • Just like C, if our string is too long, we can add \ to temporarily separate the string, and then write on the next line :: Don’t wrap the string arbitrarily::
  • String attribute length(read-only, unmodifiable attribute), returns the length of the string, and the application method isstr.length

Commonly used methods are str.method.

charAt( )
  • charAt() returns the character at the specified position in the string, and the parameters are written starting from 0
  • If the parameter is negative or exceeds the range , charAt() will return an empty string , and there will be nothing on the console ""
concat( )
  • Used to concatenate two strings , merge and return a new string without changing the original string
  • The content in brackets can be multiple! There is no limit to the parameters that can be merged
  • If the parameter is not a string, concat will first turn it into a string and then concatenate it.
  • We only need to use the + sign, and we don’t need to concat to connect
    %% There is a difference between concat and +. concat is a string method, so no matter what the parameter is, it must be turned into a string first and then connected, but if the + sign is encountered When two data types are found, operations will be performed . When numbers and strings are encountered, they will be connected.
substring( )
  • Intercept the string, take out the substring and return it without changing the original string
  • Parameter 1 represents the starting position, parameter 2 represents the end position, left closed and right open! ! ! ++For example (0, 2) will return the first two characters ++If the end position is not written, it will be read completely by default.
  • If parameter 1 > parameter 2, the substring method will automatically correct it.
  • If the parameter is a negative number, the negative number is automatically converted to 0
substr( )
  • The only difference from substring() is the parameter . Parameter 2 is the length of the substring. If omitted, it will be read by default.

If parameter 1 is negative , it means reverse order ; if parameter 2 is negative , it changes to 0, so an empty string will be returned.

indexOf() is very commonly used! ! !
  • Used to determine the position of the first occurrence of a string in another string . The return result is the starting position . If -1 is returned, it means there is no match.
  • There can also be a second parameter (data), which means searching backward starting from this position
trim( )
  • Remove spaces , tabs, line feeds, and carriage returns from both ends of the string, and return a new string without changing the original string. No parameters are required when removing
  • ES6 extension methods:
    • trimEnd(): intercept the right side
    • trimStart(): intercept the left side
  • Analogous to Python's strip function
split(): Convert string to array
  • Separate the string according to a certain specified rule and return an array composed of the separated substrings :: For example, 'it|sxt|baizhan'.split('|') returns ["it on the console ","sxt","baizhan"], what is displayed on the web page is it,sxt,baizhan::
  • If the split('') parameter is an empty string, this method splits each character
  • If nothing is written in the parameter, the content in the array will be the complete original string.
    • This is different from Python. Note that the original string will be returned without writing parameters.
  • The split method can have parameter 2, which limits the maximum number of members of the returned array.

array

Overview

  • Arrays can be defined first and then assigned . let arr1=[];arr1[0]=1;There is no limit on the number. They are variable arrays!
  • Any type of data can be put into the array at will, and the types of elements in the array can be different.
  • Multidimensional arrays: nesting of arrays
  • length attribute: returns the number of members of the arrayarray.length
  • Returns when the array exceeds the boundsundefined

Array traversal! ! ! !

  • for...inUsed to traverse all elements
    `` for(var i in arrayname){…}

method

Array.isArray()
  • Determine whether a content is an array and return a Boolean value::to make up for the shortcomings of the typeof operator::
  • It looks like this . The name is in the brackets. If it is an array, it returns true.
push()/pop()
  • push() is used to add one or more elements to the end of the array , and returns the number of added elements::push() will change the original array::++ This returned number is for human use, for example, you want to wait until If you want to count length=arr.push(...), just use var. If you don’t want to know, just use it as a statement++
  • pop() is used to remove the last element of the array and return that element
shift()/unshift()

%% is just the opposite of push/pop, shift() deletes the first element and returns that element

  • Use shift to clear array elements:
    `` while(var i = arr.shift()){console.log(i);}

After all are cleared, i is undefined, which is false when converted to a Boolean value, and the loop exits.

  • unshift() : Add elements to the head and return the length of the array after adding the elements
join(): Convert array to string, opposite to split() method
  • Using the specified parameter as the delimiter, concatenates all array members into a string and returns it.
  • Basically, it is arr.join("")directly converted into a string without gaps. If no parameters are provided, they will be separated by commas by default. If the array members are null/undefined, they will be converted into empty strings during connection::There is nothing::
concat(): Combine multiple arrays into one array
  • The parameter does not have to be an array, it can be of any type . If you just add elements, it feels the same as push().
  • Application scenario: Pull up to load, merge data ++ For example, when browsing Moments, the information we observe is assumed to be stored in an array. If we want to see longer Moments, we just pull down, and the background will send the data. At this time, the data will be merged between them. The merging of arrays is implemented by concat++
reverse(): used to reverse the array elements, this method will change the original array
  • Used to reverse the order of a string ! First convert the string into an array split(), then reverse the order of the array, joinand then convert the array into a string
indexOf(): Search and return the position where the element first appears in the array, no return -1
  • Use arr.indexOf(元素)>-1judgment to determine whether it exists
  • There is also a second parameter, indicating the starting position

function

  • functionFunction declaration command: function+function name+(formal parameter){}
  • Just write the name of the function call directly
  • Function name promotion
    • The JS engine treats function names as variable names . functionWhen a function is declared using a command, the entire function is promoted to the head of the code just like a variable.
    • To put it bluntly: it is feasible for you to call the function first and then declare it: variable promotion only raises the declaration, not the initialization. But the function will improve the whole, so you can call the function in advance and realize the function of the function::
    • Variable promotion is before function promotion . No matter what is encountered, variable promotion is always carried out first, and then function promotion is performed after promotion:: The effect of function promotion is similar to that of shearing, but function promotion will not occur early after JS parsing. On variable promotion::
  • Function parameters: Just write the formal parameter name directly , without specifying the data type of the formal parameter, such as `fuction add(x,y){console.log(x+y);}
  • The return value is optional! , you can write it returnor not! But note that as long as we write return, no codereturn statement can be added after return. It must be written at the end of the function, and other codes must be written in advance, otherwise it will not work.

object

Overview

%% Object is the core concept of JS and the most important data type. The object is a set of "key-value pairs". It is an unordered composite data collection and is very inclusive. For example:
var user = { name:'zhangyiteng',
GetName:function(name){return name;},//At this time, GetName is the function name, and the attribute is the function name.
container:{frontEnd:'web'},age:19
`` };

  • Each key name of the object is also called a property , and the value can be any data type. If the value of an attribute is a function , then the entire attribute is usually called a method :: Function and method have the same meaning, so there is no need to go into detail::
  • Just call the functionuser.GetName(名字);
  • If objects are nested, the members we call the members of the object are called chain calls, such asuser.container.frontEnd

Math object

  • Math.abs() absolute value , just pass in the value later
  • Math.max()/min()
    • A lot of parameters: return the maximum and minimum values
    • No parameters: min returns -Infinity, max returns Infinity
  • Math.floor()/ceil()
    • floor(): round down
    • ceil(): round up
  • Math.random(): Returns a random number between [0,1) without writing parameters
  • Math.round(): rounding

Date object

%% takes 0:00:00 on January 1, 1970 (Greenwich Mean Time/International Time) as the zero point, and the range is 100 million days before and after (unit is milliseconds)

  • Date.now(): Gets the number of milliseconds from the current time to zero , which is equivalent to multiplying the Unix timestamp by 1000 ::now itself is useless::
    • ::The timestamp is the number of seconds from zero::The data given to us by the background is 1000 times of such numbers. We need to convert these numbers into time ourselves.
    • Unix is ​​an operating system that appeared in the early 1970s. Unix considers 1970-01-01-0 to be the time epoch , so JS follows the Unix timestamp.
  • Convert timestamp to full long date format
    • Given a timestamp usenew Date(时间戳114514114514)
    • Use the current timenew Date()
    • Given date in Englishnew Date('January 6,2022')
    • The input parameters are year, month, day, hour, minute and second.
  • A series of get methods: return specific partial values ​​based on the date, for example: console.log(new Date().getDate())what is printed is the day of the current time
    • Time(): Get the timestamp in milliseconds
    • Day(): day of the week, Sunday is 0, Monday is 1, and so on
    • Year(): Number of years from 1900
    • FullYear(): four-digit year
    • Month(): 0 means January, 11 means December
    • Hours(): 0-23 hours
    • Milliseconds(): 0~999 milliseconds
    • Minutes(): Minutes 0~59
    • Seconds(): Seconds 0~59
      %% Generally, a variable d is created to store the date format, and then d.get... is used to use the function

おすすめ

転載: blog.csdn.net/qq_65052774/article/details/135051866