zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Basic Syntax of JavaScript

During the process of learning the basic syntax of JS, I recorded the knowledge points and questions encountered for future review and reference.

Data types include: data, string, array, number, boolean, etc.

1. Data Types#

1. Number#

2. Boolean#

There are only two values: true and false, which can be directly expressed as true and false, for example:

true;	//true
false;	//false
2>1;	//true
2>3;	//false

And &&
Both must be true for the operation result to be true.

Or ||
If at least one is true, the operation result is true.

Not !
When the program is true, the operation result is negated to false.

var age = 15;
if(age >= 18) {
    alert('adult')
}else{
    alert('teenager')
}

The value of age is 15. When age is greater than or equal to 18, the browser pops up 'adult', otherwise it pops up 'teenager'.

3. String#

4. Comparison Operators#

== and ===

When using == for comparison, it generally performs type conversion automatically before comparing.

When using === for comparison, if the data types are different, it directly returns false, and only when the types are the same does it proceed to compare.

A special number is NaN, which is not equal to any value, including itself NaN.

NaN === NaN	//false

5. null and undefined#

null represents a null value, 0 represents a numeric value, '' represents a string of length 0, but null indicates emptiness.

undefined indicates that something is undefined.

However, distinguishing between the two is not very significant; most still use null, while undefined is only useful in determining whether function parameters were passed.

6. Array#

[ ] represents a collection of values arranged in order, where each value is called an element.

new Array(1,2,3)	//[1,2,3]

Array Index

2. Objects and Variables#

var person = {
	name: 'jack',
	age: 20,
	city: 'hangzhou'
}

person is an object variable, and name: 'jack' is a key-value pair, where name is the property name and 'jack' is the value.

To access a property of an object, use object variable.property, which is person.name, resulting in jack.

person.name	//jack
person.age	//20

var is a dynamic language; even if var defines x = 100, later x = x + 100 changes it to 200.

var x = 100;
x = x + 100;
console.log(x)	//200

If int were used to define x, the subsequent x = x + 100 would result in an error.

Moreover, variables defined using var only exist within the scope of that function and are not global by default.

If var is not used and i = 100 is defined directly, the variable i will be treated as a global variable.

3. Strings#

Escape characters \ are needed.

1. Template Strings#

var name = '小明';
var age = 20;
var message = name + '今年' + age + '了';
//小明今年20了
var message = `${name},你今年${20}了`
//ES6 new syntax, same result

Strings are immutable

If you assign a value to a specific index of a string, it will not throw an error and will not change anything.

var a = 'hello,world!'
a[0];	//h
a[0] = k;
console.log(a);	//result is 'hello,world!', no change

2. toUpperCase#

It returns a new string, converting the entire string to uppercase.

var a = 'hello';
a.toUpperCase();	//returns HELLO

3. toLowerCase#

It returns a new string, converting the entire string to lowercase.

var a = 'hello'
a.toLowerCase();	//HELLO

4. indexOf#

It returns the index of the specified string; if the specified string is not found, it returns -1.

var a = 'hello,world!'
a.indexOf('world');	//6

5. substring#

It returns the substring of the specified index range, including the first number but excluding the last number.

var a = 'hello,world!'
a.substring(0, 5);	//hello

If there is only one number in (), it starts from that index until the end, for example:

var a = 'hello,world!';
a.substring(6);	//returns world!

4. Arrays#

Arrays Array can contain any type of data and can be accessed by index.

1. length Property#

The length of an Array can be obtained using the length property, which is different from the index, starting from 1.

var arr = [1,2,3,'hello',null,true]
arr.length;	//returns 6

By changing the value of length, you can change the size of the array.

var arr = [1,2,3,'hello',null,true]
arr.length;	//6
arr.length = 8;	//[1,2,3,'hello',null,true,undefined,undefined]
arr.length = 2;	//[1,2]

2. Changing Array by Index#

Array can be modified directly by index.

var arr = [1,2,3]
arr[1] = 'hello'
console.log(arr); 	//[1,'hello',3]

JS allows changing the length of an array directly by index without throwing an error, but it is not recommended.

3. indexOf#

Array can use indexOf to search for the index of a specified element.

var arr = [1,2,3,'hello']
arr.indexOf(1);	//0
arr.indexOf(3); //2

4. slice#

The slice method is similar to substring, the latter extracts the content of a string, while slice extracts the content of an array and returns a new array.

If there are two numbers, it includes the first number but excludes the second; if there is only one number, it counts from that number to the end.

var arr = [1,2,3,4,5];
arr.slice(0,2);	//returns [1,2]
arr.slice(2);	//returns [3,4,5]

If slice does not specify numbers, it returns all contents of the array, which can be used to copy an identical array.

var arr = [1,2,3];
var arr1 = arr.slice();
console.log(arr1);	//[1,2,3]
arr1 === arr;	//false

Note: Comparing two arrays will always be false, even if their contents are the same.

var arr = [1,2,3]
var arr1 = [1,2,3]
arr === arr1	//false

5. push and pop#

push() adds an element to the end of the array.

pop() removes the last element from the array.

6. unshift and shift#

unshift() adds an element to the beginning of the array.

shift() removes the first element from the array.

7. sort#

sort() can sort an array and will directly modify the positions of the current array elements; when called directly, it will sort in the default way.

var arr = [B,A,C]
arr.sort();
arr	//[A,B,C]

8. reverse#

reverse() will reverse the entire array, not sort it in reverse order.

var arr = [2,1,3]
arr.reverse();
arr;	//[3,1,2]

9. splice#

This method is versatile; by calling splice(), you can delete or add elements from a specified index.

5. Conditional Statements#

In JS, use if() {...} else {...} for conditional statements.

var age = 22;
if(age>20) {
	// If age > 20 is true, execute this statement
	console.log('22>20')
}else {
	// If age > 20 is false, execute this statement
	console.log('22<20')
}

Ultimately, the console will print 22>20 because the condition is true.

The executed statements should be wrapped in {} to prevent errors in other situations.

Multiple Conditional Statements

Three or more conditional statements are called multiple conditional statements.

var a = 10
if(a<10) {
	console.log('a<10')
}else if(a>20){
	console.log('a>10')
}else{
	console.log('10<=a<=20')
}

If multiple conditions are satisfied, the first satisfied result will be taken, and its code will be executed, while subsequent satisfied conditions will be ignored. Therefore, when making conditional judgments, do not repeat conditions.

A complex multiple conditional statement:

var height = parseFloat(prompt('Please enter your height (m):'));
var weight = parseFloat(prompt('Please enter your weight (kg):'));
var bmi = weight/(height*height);
if(bmi < 18.5) {
	console.log('Underweight')
}else if(bmi>18.5 && bmi<25) {
	console.log('Normal')
}else if(bmi>25 && bmi<28){
	console.log('Overweight')
}else if(bmi>28 && bmi<32){
	console.log('Obese')
}else{
	console.log('Severely Obese')
}

parseFloat can parse a string and return a number.

6. Loops#

Simple calculations can be done by hand:

1 + 2 + 3
// Console outputs 6 

However, calculations in the hundreds, thousands, or tens of thousands cannot be done by hand and can rely on loop statements for computation, allowing the computer to perform calculations thousands of times.

There are two types of loop statements: for and while, each with different uses suitable for different situations.

1. For Loop#

Loops through a block of statements based on initial conditions, end conditions, and increment conditions.

var x = 0
var i
for(i = 1; i <= 1000; i++) {
	x = x + i
}

i = 1 is the initial condition, starting from 1.
i <= is the judgment condition; if true, it executes the loop; if false, it exits the loop.
i++ is the increment condition; after each loop, it adds 1. When it no longer satisfies i <= 1000, it exits the loop.

2. Iterating through an Array with for Loop#

var arr = ['apple', 'banana', 'orange']
var x,i
for(i = 0; i < arr.length; i++) {
	x = arr[i]
	console.log(x)
}

3. Using break to Terminate for Loop#

var x = 0;
for (  ;  ;  ) { // This will loop infinitely
    if (x > 100) {
	console.log(x)
	break; // Exit the loop based on the if condition
    }
    x ++;
}

4. for...in#

Can loop through the properties of an object.

var person = {
	name: 'jack',
	age: 20,
	city: 'beijing'
};
for(var i in person) {
	console.log(i)
	console.log(person[i])
}

var i in person will iterate through all properties in person, and console.log(i) will print the property names, while console.log(person[i]) will print the property values.

If you perform this operation on an array, it will print the indices of the array elements, and the printed result will be in string form.

5. While Loop#

while loops are suitable for situations where the judgment condition is ignored, while for is suitable for situations where the initial and end conditions are clear.

For example, to calculate the sum of odd numbers between 1 and 100, you can use a while loop.

var x = 0
var n = 99
while (n > 0) {
	x = x + n
	n = n - 2
}
x

In the variable, n continuously decreases, directly reaching n = -1, which does not satisfy the judgment condition, at which point it exits the loop.

6. do...while#

do...while loops first execute the loop and then check the condition, so regardless of whether the condition is met, do...while will loop at least once, which distinguishes it from for and while.

For example:

var n = 0
do{
	n = n + 1
}while(n > 1)
n;	//1

First, n=0 is defined, then n=n+1 is executed, so n=1, and then the condition is checked. When n > 1 is executed, it does not meet the condition, exits the loop, and the console outputs n, resulting in 1.

7. Map and Set#

1. Map#

Map is a structure of key-value pairs with extremely fast lookup speeds.

As long as we define an array corresponding to a property name and value, we can directly look up data from this array by name.

var m = new Map([['jack', 95], ['Bob', 94], ['linda', 93]])
m.get('jack')

First, initialize a Map array.

var m = new Map();	//empty map
m.set('jack', 95)	//add a new key-value pair		key-value
m.has('jack')		//check if 'jack' key exists
m.get('jack')		//get the data corresponding to 'jack'		value
m.delete('jack')	//delete 'jack' key-value pair		key-value
m.get('jack')		//undefined

A key can only correspond to one value, so if assigned again, the latter data will overwrite the former.

var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam'); // 88

2. Set#

Set stores keys but not values, and in Set, keys cannot be duplicated; if duplicated, it will automatically ignore the duplicates.

First, create an empty set.

var m = new Set()	//empty set
m.add(1)			//add a key
m.delete(1)			//delete a key
m	//console outputs [] empty array, no data
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.