Supplementary explanation of data types, constructors, prototypes, and prototype chains
I. Data Types#
1. 5 Primitive Types#
string
number
boolean
undefined
null
symbol
The most common ones are strings, numbers, and booleans.
2. Common Reference Types#
Reference types are data structures used to organize data and functionality.
Object - Object, Array - Array, Function - Function, RegExp - RegExp, Date - Date, etc.
II. Functions#
1. What is a Function?#
- A code block with independent functionality, defined using the function keyword in JavaScript.
- Makes the code structure clearer and improves code usability.
- Categories of JavaScript functions: custom functions and built-in functions.
2. Custom Functions#
There is a type of function called an anonymous function, which is a function without a name. It creates closures to avoid polluting the global scope.
Anonymous self-invoking function
- Concept: Immediately executes the definition of the anonymous function, executing the function expression.
- Purpose: Implement closures and create independent namespaces.
- Usage: Grouping operator (), void operator, ~ operator, ! operator, etc.
- Use cases: function expressions, object properties, events, event parameters, return values.
- After defining an anonymous function, it must be called.
// Function expression
window.onload = function() {
let funcobj = function() {
alert("Anonymous function in function expression")
}
funcobj();
}
// Object property
window.onload = function() {
let obj = {
name: function() {
alert('Anonymous function in object property')
}
}
obj.name();
}
3. Built-in Functions#
Functions placed under the global scope are called functions, while functions placed inside objects are called methods, which are object methods.
- Regular Functions
alert() // Displays an alert box
confirm() // Displays a confirmation box
prompt() // Displays an input box
isNaN() // Checks if a value is NaN
parseInt() // Converts a string or floating-point number to an integer
parseFloat() // Converts a string to an integer or floating-point number
eval() // Evaluates the result of an expression
- Array Functions
Traversing an array using a for loop
var arr = [1,2,3,4];
for(var i = 0; i<arr.length; i++) {
console.log(arr[i])
}
// Output: 1,2,3,4
Traversing an array using for...in
var arr = [1,2,3,4];
for (var i in arr) {
console.log(arr[i]);
}
// Output: 1,2,3,4
// Adding elements
unshift() // Adds elements to the beginning of an array and returns the new length of the array
push() // Adds elements to the end of an array and returns the new length of the array
concat() // Joins two arrays and returns the resulting array
var arr1 = [1];
var arr2 = [2];
let arr = arr1.concat(arr2);
console.log(arr); // [1,2]
/*****************************************/
// Removing elements
pop() // Removes the last element of an array and returns the removed element
shift() // Removes the first element of an array and returns the removed element
splice(a,b) // Removes b elements starting from position a in the array and returns the removed elements
slice(a,b) // Removes elements between positions a and b in the array
/*****************************************/
// Searching
indexOf() // Checks if an array contains a specified element. Returns the element if it exists, or -1 if it doesn't
includes() // Checks if an array contains a specified element. Returns true if it exists, or false if it doesn't
/*****************************************/
// Others
sort() // Sorts the array according to a specified rule
var arr1 = [4,5,6];
var arr2 = [1,2,3];
var arrAscSort = arr5.sort((a, b) => a-b); // Ascending sort
console.log(arrAscSort); // [ 1, 1, 2, 3, 5, 6 ]
var arrDescSort = arr5.sort((a, b) => b-a); // Descending sort
console.log(arrDescSort); // [ 6, 5, 3, 2, 1, 1 ]
reverse() // Reverses the array
var arr = [1,2,3,4,5,6];
// Directly calling the reverse() method
console.log(arr.reverse()) // [6,5,4,3,2,1]
Array.from() // Converts a string of characters into an array
var str = 'Converts a string of characters into an array'
console.log(Array.from(str))
// ["C", "o", "n", "v", "e", "r", "t", "s", " ", "a", " ", "s", "t", "r", "i", "n", "g", " ", "o", "f", " ", "c", "h", "a", "r", "a", "c", "t", "e", "r", "s", " ", "i", "n", "t", "o", " ", "a", "n", " ", "a", "r", "r", "a", "y"]
Array.isArray() // Checks if a variable is an array
var str = 'Converts a string of characters into an array'
console.log(Array.isArray(str))
// false
- Date Functions Date()
Getting the time
var time = new Date()
// Get the current time
// Fri Nov 13 2020 20:21:35 GMT+0800 (China Standard Time)
getFullYear() // Get the current year
getMonth() // Get the current month (0-11)
getDate() // Get the current day of the month
getHours() // Get the current hour
getMinutes() // Get the current minute
getSeconds() // Get the current second
getMilliseconds() // Get the current millisecond
getTime() // Get the timestamp - the number of milliseconds since January 1, 1970
Setting the time
setYear() // Set the year
setMonth() // Set the month
setDate() // Set the day of the month
setHours() // Set the hour
setMinutes() // Set the minute
setSeconds() // Set the second
- Math Functions
Mainly used mathematical functions and methods
Math.abs() // Absolute value
Math.ceil() // Rounds up to the nearest integer
Math.floor() // Rounds down to the nearest integer
Math.round() // Rounds to the nearest integer
Math.random() // Generates a random number between 0 and 1
Extended usage of random() - generating a random number with a specified number of digits
function getRandomNumber(min, max){
return Math.floor(Math.random()*(max - min)) + min;
}
console.log(getRandomNumber(1000, 9999));
- String Functions
indexOf() // Searches for a string and returns the index value
var arr = ["C", "h", "a", "r", "a", "c", "t", "e", "r", " ", "F", "u", "n", "c", "t", "i", "o", "n", "s"]
console.log(arr.indexOf("F")) // 10
split() // Splits a string into an array of substrings using a specified separator
var str = "Character Functions"
console.log(str.split('')) // ["C", "h", "a", "r", "a", "c", "t", "e", "r", " ", "F", "u", "n", "c", "t", "i", "o", "n", "s"]
trim() // Removes whitespace from both ends of a string
var str = " Character Functions "
console.log(str) // [ Character Functions ]
console.log(str.trim()) // [Character Functions]
match() // Searches for a value according to a specified pattern
var str = "Character Functions"
console.log(str.match(/Character/)) // Character
document.write(str.match(/Character/)) // Character
search() // Returns the position of the first occurrence of a specified value in a string
var str = "Character Functions"
console.log(str.search('F')) // 10
replace() // Replaces a specified string with another string
var str = "Character Functions"
console.log(str.replace('C','F'))
// Fharacter Functions
substring(a,b) // Extracts the characters from a string, between two specified positions (left-closed, right-open)
// Extracts from index a to b
var str = "Character Functions"
console.log(str.substring(0,3)) // Cha
substr(a,b) // Extracts a specified number of characters from a string, starting from a specified position
// Extracts b characters starting from index a
var str = "Character Functions"
console.log(str.substr(0,3)) // Cha
```