zishu's blog

zishu's blog

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

Some supplementary summaries about JavaScript functions and methods


slug: 17
title: Supplementary Summary on JavaScript Functions and Methods
date: 2020-11-14 12:57:00
updated: 2021-11-29 13:19:52
categories:
- Technology
tags:
- Notes
- JavaScript

Supplementary explanation on data types, constructors, prototypes, and prototype chains

1. Data Types#

1. 5 Primitive Types#

string
number
boolean
undefined
null
symbol

The most common ones are still the first three: strings, numbers, and booleans.

2. Common Reference Types#

Reference types are a kind of data structure used to organize data and functionality together.

Object - Object, Array - Array, Function - Function, RegExp - RegExp, Date - Date, etc.

2. Functions#

1. What is a Function?#

1. A code block with independent functionality, defined using the function keyword in JavaScript.
2. Makes the code structure clearer and improves code usability.
3. 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 and creates closures to avoid polluting the global variables.

Anonymous self-invoking function

1. Concept: The definition of an anonymous function is immediately executed, executing the function expression.
2. Purpose: Implement closures and create independent namespaces.
3. Usage: Grouping operators (), void operator, ~ operator, ! operator, etc.
4. Use cases: function expressions, object properties, events, event parameters, return values.
5. 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, object methods.

1. Regular functions

alert() // Pop-up box
confirm() // Pop-up confirmation box
prompt() // Pop-up input box
isNaN() // Check if it is a number
parseInt() // Convert a string or floating-point number to an integer
parseFloat() // Convert a string to an integer or floating-point number
eval() // Calculate the result of an expression

2. Array functions

Traverse the 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

Traverse the array using for in

var arr = [1,2,3,4];
for (var i in arr) {
    console.log(arr[i]);
}

// Output: 1,2,3,4
// Add
unshift() // Add an element to the beginning of the array, returns the length of the array
push() // Add an element to the end of the array, returns the length of the array
concat() // Concatenate two arrays, returns the concatenated array
    var arr1 = [1];
    var arr2 = [2];
    let arr = arr1.concat(arr2);
    console.log(arr); // [1,2]

/*****************************************/
// Delete
pop() // Delete the last element of the array, returns the deleted element
shift() // Delete the first element of the array, returns the deleted element
splice(a,b) // Delete b elements after position a, returns the deleted elements
slice(a,b) // Delete elements between position a and b

/*****************************************/
// Search
indexOf() // Check if the array contains a specific element, returns the element if it exists, -1 if it doesn't
includes() // Check if the array contains a specific element, returns true if it exists, false if it doesn't

/*****************************************/
// Others
sort() // Sort the array according to the rules
    var arr1 = [4,5,6];
    var arr2 = [1,2,3];

    var arrAscSort = arr5.sort((a, b) => a-b); // Ascending order
    console.log(arrAscSort); // [ 1, 1, 2, 3, 5, 6 ]
    
    var arrDescSort = arr5.sort((a, b) => b-a); // Descending order
    console.log(arrDescSort); // [ 6, 5, 3, 2, 1, 1 ]

reverse() // Reverse the array
    var arr = [1,2,3,4,5,6];
    // Directly call reverse() method
    console.log(arr.reverse()) // [6,5,4,3,2,1]

Array.from() // Convert a string of data into an array
    var str = 'Convert a string of data into an array'
    console.log(Array.from(str))
    // ["C", "o", "n", "v", "e", "r", "t", " ", "a", " ", "s", "t", "r", "i", "n", "g", " ", "o", "f", " ", "d", "a", "t", "a", " ", "i", "n", "t", "o", " ", "a", "n", " ", "a", "r", "r", "a", "y"]

Array.isArray() // Check if a variable is an array
    var str = 'Convert a string of data into an array'
    console.log(Array.isArray(str))
    // false

3. Date function Date()

Get time

var time = new Date()
// Get current time
// Fri Nov 13 2020 20:21:35 GMT+0800 (China Standard Time)

getFullYear() // Get the current year
getMonth() // Get the current month -1
getDate() // Get the current date
getHours() // Get the current hour
getMinutes() // Get the current minute
getSeconds() // Get the current second
getMilliseconds() // Get the current millisecond
getTime() // Timestamp - Get the number of milliseconds from 1970 to now

Set time

setYear() // Set the year
setMonth() // Set the month
setDate() // Set the date
setHours() // Set the hour
setMinutes() // Set the minute
setSeconds() // Set the second

4. Math functions Math

Mainly used mathematical functions and methods

Math.abs() // Absolute value
Math.ceil() // Round up
Math.floor() // Round down
Math.round() // Round to the nearest integer
Math.random() // Generate a random number between 0 and 1

Extended usage of random() - Generate 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));

5. String functions

indexOf() // Find a string and return the index value
    var arr = ["C", "h", "a", "r", "a", "c", "t", "e", "r", "s", " ", "f", "u", "n", "c", "t", "i", "o", "n"]
    console.log(arr.indexOf("f")) // 12

split() // Split a string into an array using a specified delimiter
    var str = "String functions"
    console.log(str.split('')) // ["S", "t", "r", "i", "n", "g", " ", "f", "u", "n", "c", "t", "i", "o", "n"]

trim() // Remove leading and trailing spaces from a string
    var str = "   String functions   "
    console.log(str) // [   String functions   ]
    console.log(str.trim()) // [String functions]

match() // Find values according to specified rules
    var str = "String functionsString functions"
    console.log(str.match(/String/)) // String
    document.write(str.match(/String/)) // String

search() // Return the position of the first occurrence of a string
    var str = "String functionsString functions"
    console.log(str.search('f')) // 12

replace() // Replace a specified string
    var str = "String functionsString functions"
    console.log(str.replace('S','F'))
    // Ftring functionsString functions

substring(a,b) // Cut a string from a specified position, left-closed and right-open
    // Cut from index a to b
    var str = "String functionsString functions"
    console.log(str.substring(0,3)) // Str

substr(a,b) // Cut a specified number of characters from a specified position
    // Start from index a and cut b characters
    var str = "String functionsString functions"
    console.log(str.substr(0,3)) // Str
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.