[Lesson 8] JS basic syntax; string Api

target

  • Understand JS basic syntax
    • How to create variables
    • The difference between let, var and const
    • Understand and master process control and other related grammar
    • deconstruction
    • Template string
  • Master string Api

Development process of ES6

ECMAScript 6.0 (ES6) is a new generation standard of JavaScript language. It was officially released in June 2015. Its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise development language. The relationship between ECMAScript and JavaScript is that the former is the specification of the latter and the latter is an implementation of the former. The two words can be interchanged in daily occasions of

Before ES6, JavaScript language was very backward, and many modern features were not available, which was difficult to support the development of large-scale applications. The release of ES6 completely changed JavaScript.

At present, the version upgrade of ES has become a continuous rolling process. The standards committee finally decided that the standard will be officially released in June every year as the official version of that year. In the following time, we will make changes on the basis of this version. We know that in June of the next year, the draft will become the version of the new year. In this way, we don't need the previous version number, but only need to mark it with the year.

ES6 was released in 2015, also known as ES2015. Since then, the versions released every year have changed very little. Therefore, ES6 is both a historical term and a general reference, covering all standards after ES6. Therefore, we simply think that ES6 refers to the "new generation of JavaScript". At the beginning of release, ES6 faced many compatibility problems, The mainstream JavaScript engine is not well supported, and usually needs tools such as Babel to escape. Now we can directly execute the native ES6 code with the help of the latest JS engine.

ES6 contains a lot of content. This course will not explain the basic syntax of JavaScript too much. This part needs to be learned by yourself. Here we mainly introduce the use of some common APIs. If you want to skillfully use JavaScript, you need to master the common APIs first.

jQuery has completed its historical mission. Many of its API s have now become standards and have been supported natively. jQuery will not be involved in our later courses and is not allowed to be used in assignments. The content of this chapter assumes that the students have completed the self-study of JS related basic knowledge required above.

Basic grammar

let

ES6 adds the let command to declare variables. Its usage is similar to var. the difference is that it is only valid in the code block declared by let, and let cannot be declared repeatedly in the same scope. We suggest using let instead of VaR in normal development.

function varTest() {
  var x = 1

  if (x === 1) {
    var x = 2 // Two x's are the same variable
    console.log(x)
    // Output: 2
  }

  console.log(x)
  // Output: 2
}
function letTest() {
  let x = 1

  if (x === 1) {
    let x = 2 // Two x are different variables
    console.log(x)
    // Output: 2
  }

  console.log(x)
  // Output: 1
}

In addition, at the top of programs and methods, variables declared by var will add attributes to global objects, but let will not, for example:

var x = 'hello'
let y = 'hello'

console.log(this.x) // "hello"
console.log(this.y) // undefined

The above this depends on the execution environment. For example, it is executed in the browser and points to the window object, such as node JS, pointing to the global object.

In addition, it should be noted that let s cannot be declared repeatedly in the same scope, for example:

if (flag) {
  let test = 1
  let test = 2 // SyntaxError
}

Braces {} can be used to define a block level scope.

const

Const constants are also block level, which is similar to let, but the declared value of const cannot be changed or re declared, and the global constant will not become the attribute of window object. Therefore, the constant must specify its value when declared.

const number = 123

number = 456 // Uncaught TypeError: Assignment to constant variable

Generally, we recommend that all constants be declared in uppercase letters, for example:

const MY_NUMBER = 123

It should be noted that if const is used to define arrays or objects, it is allowed to modify their children or attributes, but it cannot re assign values to itself, for example:

const MY_ARRAY = [1, 2, 3]
MY_ARRAY.push(4) // allow
MY_ARRAY = [] // not allow

const MY_OBJECT = { key: 123 }
MY_OBJECT.key = 456 // allow
MY_OBJECT = { key: 456 } // not allow

If you want to freeze the modification of object properties, you can use object The object is immutable when free(), for example

const MY_OBJECT = { key: 123 }
Object.freeze(MY_OBJECT)
MY_OBJECT.key = 456 // This statement will not work in normal mode, but it will not report an error. In strict mode, it will report an error

practice

Find and summarize the differences between var, let and const through practice.

Boolean and relational operators

Relational operator

operatordescribe
==be equal to
===Absolute equal to (value and type)
!=Not equal to
!==Absolute inequality
>greater than
<less than
<=Less than or equal to
>=Greater than or equal to

Comparison results of special cases

expressionresult
null == undefinedtrue
"NaN" == NaNfalse
5 == NaNfalse
NaN == NaNfalse
NaN != NaNtrue
false == 0true
true == 1true
true == 2false
undefined == 0false
null == 0false
"5" == 5true

Boolean operator

operatordescribe
&&and
||or
!not

practice

When these operators are used for comparison, type conversion occurs. ***

Additional: other operators

In addition to these two operators, there are other operators, such as unary operator, comma operator, etc. Please understand them yourself.

Cast type

When using the above two operators, type conversion will be carried out. Please understand it yourself after class.

program control

if...else

if(a == 1) {  console.log('a=1');} else if(a == 2) {  console.log('a=2');} else {  console.log('a=other');}

switch...case

switch(n) {  case 1: {    break  }  case 2: {    break  }  default: {  }}

for loop

for(let i = 0; i < 10; i++) {  if(i%2==0) {    continue;  }  console.log(i)}

while Loop

while(true) {  console.log("true");}

practice

Guessing numbers games:
Set a puzzle number, input a four digit number, and output a character to indicate whether you are right

  • For example, the number to be solved is 1234
    • Guess 1233, then output 3A1B
    • Guess 1234, then 4A0B is output

Think: besides for and while, what other loop methods are there

Destructuring assignment

Deconstruction assignment syntax is a JavaScript expression. By deconstruction assignment, attributes and values can be taken from objects and arrays and assigned to other variables. Previously, if we wanted to assign values to variables, we could only directly specify the values of variables, for example:

let a = 1let b = 2let c = 3

If we want to get the value from the array, we need to write this:

let array = [1, 2, 3]let a = array[0]let b = array[1]let c = array[2]

If we want to extract properties and values from objects, we need to write them as follows:

let object = { a: 1, b: 2, c: 3 }let a = object.alet b = object.blet c = object.c

From the above example, we can see that the writing is very cumbersome and not concise enough. Now we can easily implement it through the deconstruction assignment syntax of ES6.

Deconstruct array

The basic syntax is as follows. The variable names on the left correspond to the elements in the array on the right one by one

let [a, b, c] = [1, 2, 3]console.log(a) // 1console.log(b) // 2console.log(c) // 3

You can set default values for variables in the left array, such as

let [a = 1, b = 2] = [5]console.log(a) // 5console.log(b) // 2

Two variables can be exchanged directly through deconstruction. When there is no deconstruction, we need an intermediate temporary variable

let a = 1let b = 2// Do not use deconstruction to exchange let c = aa = bb = c / / use deconstruction to exchange [(a, b)] = [b, a] console log(a) // 2console. log(b) // 1

A common scenario for deconstructing an array is to parse the return value of a function, such as

function foo() {  return [1, 2]}let [a, b] = foo()console.log(a) // 1console.log(b) // 2

Some values can be ignored. for example

let [a, , , b] = [1, 2, 3, 4]console.log(a) // 1console.log(b) // 4

Residual mode, assign the remaining array to a variable

let [a, ...b] = [1, 2, 3]console.log(a) // 1console.log(b) // [2, 3]

Deconstruction object

The basic syntax is as follows:

let object = { a: 1, b: 2, c: 3 }let { a, b } = objectconsole.log(a) // 1console.log(b) // 2

You can extract a variable from an object and assign it to a new variable name different from the property name

let object = { a: 1, b: 2, c: 3 }let { a: aa, b: bb } = objectconsole.log(aa) // 1console.log(bb) // 2

Deconstruction objects can also specify default values, such as:

let object = { a: 5 }let { a = 1, b = 2 } = objectconsole.log(a) // 5console.log(b) // 2

Deconstruction objects also support residual patterns, such as

let { a, ...b } = { a: 1, b: 2, c: 3 }console.log(a) // 1console.log(b) // { b: 2, c: 3 }

A typical application scenario of deconstructing an object is to extract data from the function parameter object. For example, the following code. The parameter received by the function is an object. If deconstruction is not used, it is necessary to read the attribute value in the parameter object

function test(user) {  console.log(user.id, user.name)}let user = {  id: 1,  name: 'test',}test(user)

If we use deconstruction objects, we can take out the attributes directly

function test({ id, name }) {  console.log(id, name)}let user = {  id: 1,  name: 'test',}test(user)

Template string

Template string is an enhanced version of string, which is identified by back quotation marks (`). It can be used as an ordinary string, can also be used to define multiple lines of text, or embed variables or expressions in the string through ${}.

let a = `template string` // Ordinary string let name = 'frank'let B = ` Hello ${name}` console. log(b) // Hello Frank!

Another important function of template string is to make multi line text definition more convenient. Comparative example:

let name = 'Frank'let a = `<div>  <p>Hello ${name}!</p></div>`let b = '<div>\n  <p>Hello ' + name + '!</p>\n</div>'console.log(a === b) // true

String operation

String processing is a very common function in programming. Here are some basic string processing methods, some of which existed before ES6.

substring

This method returns a subset of a string from the start index to the end index, or from the start index to the end of the string.

grammar

parameter

  • indexStart: the index of the first character to be intercepted. The character at the index position is used as the first letter of the returned string.
  • indexEnd: optional parameter, an integer between 0 and string length. The string indexed by this number is not included in the intercepted string.

Return value

A new string that includes a specified portion of a given string

Here are some examples:

let str = '0123456789'console.log(str.substring(0, 3))  // '012'console.log(str.substring(3, 6))  // '345'console.log(str.substring(0, -3)) / / equivalent to str.substring(0, 0). The output is an empty string

slice

Slice is very similar to substring. The difference is that slice parameters can be negative numbers, indicating the penultimate character

let str = '0123456789'console.log(str.slice(0, 3))  // '012'console.log(str.slice(3, 6))  // '345'console.log(str.slice(0, -3)) // '0123456', indicating that the penultimate character console is extracted from each character 0 log(str.slice(-3, -1))  // '78'

includes

Method is used to determine whether a string is contained in another string, and returns true or false according to the situation.

parameter

  • searchString: the string to search
  • Position: the index position to start searching. The default value is 0. Optional

Example:

let str = '0123456789'console.log(str.includes('123'))  // trueconsole.log(str.includes('123', 4)) // false

startsWith

The startsWith method is used to judge whether the current string starts with another given substring, and returns true or false according to the judgment result.

parameter

  • searchString: the string to search
  • Position: the index position to start searching. The default value is 0. Optional

Example:

let str = '0123456789'console.log(str.startsWith('0123')) // trueconsole.log(str.startsWith('1234'))  // falseconsole.log(str.startsWith('1234', 1))  // true

endsWith

endsWith is similar to startsWith in that it is used to judge whether the current string ends with another given substring. The second parameter of endsWith is the optional str length. An example is as follows:

let str = '0123456789'console.log(str.endsWith('789'))  // trueconsole.log(str.endsWith('456', 7)) // true, which is equivalent to judging' 0123456 ' endsWith('456)

repeat

This method returns a new string, indicating that the original string is repeated n times. An example is as follows:

'abc'.repeat(2) // 'abcabc'

padStart,padEnd

These two methods provide the function of string completion. If a string is not long enough, it will be completed at the head or tail. padStart is used for head completion and padEnd is used for tail completion. This is very useful when formatting strings. Examples are as follows:

'5'.padStart(5, '0')  // '00005''123'.padEnd(5) // '123', the default is to fill in '12345' with spaces Padstart (4) / / '12345', it exceeds the length and will not change

trim,trimStart,trimEnd

The functions of these three methods are similar. trim is used to eliminate the spaces at the beginning and end of the string, trimStart is used to eliminate the spaces at the beginning and end of the string, and trimEnd is used to eliminate the spaces at the end of the string. They return a new string without changing the original value. Examples are as follows:

let str = '  abc  'str.trim()  // 'abc'str.trimStart() // 'abc  'str.trimEnd() // '  abc'

replaceAll

The previous string replacement method replace() of js only replaced the first match. If you want to replace all matches, you need to write a regular expression, for example:

'aabbcc'.replace('b', '_')  // 'aa_bcc''aabbcc'.replace(/b/g, '_') // 'aa__cc'

Writing regularization increases the complexity. Now the new replaceAll() method can replace all matches at one time

'aabbcc'.replaceAll('b', '_') // 'aa__cc'

split

This method uses the specified split character to split a string into a substring array, and uses a specified split string to determine the position of each split

console.log('Hello JavaScript'.split(' '))  // [ 'Hello', 'JavaScript' ]console.log('Hello'.split(''))  // [ 'H', 'e', 'l', 'l', 'o' ]

Additional: regular expressions

What is a regular expression? Understand the usage of JS regular expressions.

Keywords: Javascript Front-end JQuery

Added by johntp on Tue, 28 Dec 2021 17:21:31 +0200