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, strings, arrays, numbers, boolean values, etc.

1. Data Types#

1. Number#

2. Boolean#

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

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

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

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

Not !
When the program is true, the 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 not defined.

However, distinguishing between the two is not very significant; most still use null, while undefined is only useful in determining whether a function parameter has been 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, 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, so 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 later x = x + 100 would throw an error.

Moreover, variables defined with var only exist within the function scope 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 occurs

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 not the last number.

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

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

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

4. Arrays#

Arrays Array can contain any type of data and access each data through its index.

1. length Property#

The length of an Array can be obtained using the length property, which is different from the index and starts counting 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's content.

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 via Index#

Array can be modified directly through its index.

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

JS allows direct modification of the array's length through its index, which will not throw 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 values, it includes the first value but not the second; if there is only one value, it counts from that value 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 values, 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 return 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 of the array.

6. unshift and shift#

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

shift() removes the first element of the array.

7. sort#

sort() can sort the array, directly modifying the positions of the current array elements. When called, it sorts in the default manner.

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

8. reverse#

reverse() reverses the entire array, not sorting 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 Judgments#

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

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 Condition Judgment Statements

Three or more multiple judgment statements are called multiple condition judgment 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 is taken, and its code is executed, while subsequent satisfied conditions are automatically ignored. Therefore, when making conditional judgments, do not repeat judgment situations.

A complex multiple condition judgment statement:

var height = parseFloat(prompt('Please enter height (m):'));
var weight = parseFloat(prompt('Please enter 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 manually:

1 + 2 + 3
// Console outputs 6 

However, calculations in the hundreds, thousands, or tens of thousands cannot be done manually; loops are used for such calculations, allowing the computer to perform thousands of calculations.

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, the loop executes; if false, it exits the loop.
i++ is the increment condition; after each loop, it increases by 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 indefinitely
    if (x > 100) {
	console.log(x)
	break; // Exit the loop using if condition
    }
    x ++;
}

4. for...in#

You 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 name, while console.log(person[i]) will print the property value.

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 initial and end conditions are clearly defined.

For example, to calculate the sum of 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, and when n becomes -1, it no longer satisfies the judgment condition, exiting the loop.

6. do...while#

The do...while loop executes first and then checks the condition, so regardless of whether the condition is satisfied, do...while will loop at least once. This is its difference 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, making n=1. The condition is checked, and when n > 1 is not satisfied, it 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 property names and values, we can directly look up data from this array using the 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 the 'jack' key-value pair
m.get('jack')		//undefined

A key can only correspond to one value, so if assigned repeatedly, 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 without storing values, and in set, keys cannot be duplicated; if repeated, the duplicates will be automatically ignored.

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 an empty array []
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.