JavaScript basic notes

Built in object

  • There are three kinds of objects in JavaScript: custom object, built-in object and browser object
  • The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS, which explains the JS API
  • Built in objects refer to the built-in objects of JS language, which are used by developers and provide some commonly used or most basic and necessary functions (properties and methods)
  • The biggest advantage of built-in objects is to help us develop quickly
  • JavaScript provides several built-in objects: Math, Data, Array, String, etc

Review documents

To learn how to use a built-in object, just learn how to use its common members. We can learn by looking up documents, and we can query through rookie tutorial / MDN/W3C

How to learn methods in objects

  1. Review the function of this method
  2. Check the meaning and type of parameters inside
  3. View the meaning and type of the return value
  4. Perform demo test

Math object

Math Math object is not a constructor, so you don't need to use new to call it, but just use the properties and methods inside

  • Math.abs() takes absolute value
  • Three rounding methods:
    • Math.floor(): round down
    • Math.ceil(): round up
    • Matg.round(): rounding (. 5 special, take the larger one, - 3.5, take the larger one as - 3)
console.log(Math.PI);//3.141592653589793
console.log(Math.max(1,2,3));//3
console.log(Math.max(1,2,'psyduck '));//NaN
console.log(Math.max(1,2,'3'));//Implicit conversion converts 3 of a string to numeric 3
console.log(Math.max(0,true));//1
console.log(Math.max());//-Infinity

// 3 rounding methods
// Round down
console.log(Math.floor(1.7));//1
// Round up
console.log(Math.ceil(1.1));//2
// Round off the plate to the nearest place. Note that the result of - 3.5 is - 3 (. 5 is special, take the larger one, and - 3.5 takes the larger one)
console.log(Math.round(1.1));//1
console.log(Math.round(1.5));//2
console.log(Math.round(-1.1));//-1
console.log(Math.round(-1.5));//-1
console.log(Math.round(-1.6));//-2
  • Random number (random)
//Returns a random decimal number between 0.0 (inclusive) and 1.0 (exclusive)
console.log(Math.random());

Obtain a random integer between min (inclusive) and max (exclusive)

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

Obtain a random integer between min (inclusive) and max (inclusive)

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
 // Random roll call
 var arr=['psyduck ','Pikachu','Little fire dragon','Jenny turtle','snorlax '];
 console.log(arr[getRandom(0,arr.length-1)]);

Figure guessing game

Randomly generate a number between 1 and 10 and let the user enter a number,

  1. If it is greater than this number, it will prompt that the number is large and continue to guess
  2. If it is less than this number, you will be prompted that the number is small and continue to guess
  3. If it is equal to this number, it will prompt, guess correctly, and end the program
// 1 randomly generate numbers between 1 and 10
// 2 need to guess until it's right, so keep cycling
// 3while loop is simpler
// 4. The core algorithm uses if else if multi branch to judge whether it is greater than or equal to less than
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
var random = getRandom(1, 10);
while (true) {//Dead cycle
    var num = prompt('Guess a 1~10 Number between:');
    if (num > random) {
        alert('The number is big,Keep guessing');
    } else if (num < random) {
        alert('The number is small,Keep guessing');
    } else {
        alert('You guessed right');
        break;
    }
}

Guess the number between 1 and 100, but there are only 10 chances

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
var random = getRandom(1, 100);
for (var i = 10; i >= 1; i--) {
    var num = prompt('Guess a 1~10 Number between:');
    if (num > random) {
        alert('The number is big,Keep guessing');
    } else if (num < random) {
        alert('The number is small,Keep guessing');
    } else {
        alert('You guessed right');
        break;
    }
}

Date object

The Date object is different from the Math object. It is a constructor and must be created using new

// Date is a constructor and must be created using new
var arr = new Array();//Create an array object
var obj = new Object();//Create an object instance
//1. Use Date. If there is no parameter, return the current time of the current system
var date = new Date();
console.log(date);
// 2. Common writing method of parameters: numeric type 1997,10,1 or string type '1997-10-1 18:8:8'
var d1= new Date(2021,10,1);
console.log(d1);//November is returned, not October!!!!!! The returned month is one month smaller (0 ~ 11)
var d2= new Date('2021-10-1 13:11:8');
console.log(d2);//Return to normal

Date formatting

view code

// Date format date
var day = new Date();
console.log(day.getFullYear());//Returns the year of the current date
console.log(day.getMonth());//1 should be returned, but 0 is returned here (because the month returns 0 ~ 11, it is smaller than 1)
console.log(day.getMonth() + 1);//Remember + 1
console.log(day.getDate());//Return number
console.log(day.getDay());//Returns the day of the week, Monday returns 1, Saturday returns 6, but Sunday returns 0!!!
//Write a Tuesday, January 18, 2022 in this format
var year = day.getFullYear();
var month = day.getMonth() + 1;//Pay attention to add 1
var date = day.getDate();
var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
//Because the index number of Sunday is 0 
var week = day.getDay();
console.log('Today is:' + year + 'year' + month + 'month' + date + 'day ' + arr[week]);


// Date format hour minute second
console.log(day.getHours());//Time
console.log(day.getMinutes());//branch
console.log(day.getSeconds());//second
//The encapsulation function returns the current time, minute and second format 08:08:08
function getTimer() {
    var time = new Date();
    var h = time.getHours();
    h = h < 10 ? '0' + h : h;//If it is less than 10, add a 0 in front of it and display it in the form of 01
    var m = time.getMinutes();
    m = m < 10 ? '0' + m : m;
    var s = time.getSeconds();
    s = s < 10 ? '0' + s : s;
    return h + ':' + m + ':' + s;
}
console.log(getTimer());


// The following method: returns the number of milliseconds (timestamp) between now and January 1, 1970
//1. Use valueof() getTime()
var date = new Date();
console.log(date.valueOf());
console.log(date.getTime());
//2. Simple writing method (the most commonly used writing method)
var date1 = +new Date();//Returns the total milliseconds of the current time, or you can add a parameter to () to return the total milliseconds of the specified time
console.log(date1);
//3.H5 NEW 
console.log(Date.now());

Countdown effect

function countDown(time) {
    var nowTime = +new Date();//Returns the total milliseconds of the current time
    var inputTime = +new Date(time);//Returns the total milliseconds of user input time
    var times = (inputTime - nowTime) / 1000;//Milliseconds to seconds
    var d = parseInt(times / 60 / 60 / 24);
    d = d < 10 ? '0' + d : d;
    var h = parseInt(times / 60 / 60 % 24);
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60);
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60);
    s = s < 10 ? '0' + s : s;
    return d + 'day' + h + 'Time' + m + 'branch' + s + 'second';
}
console.log(countDown('2022-1-19 18:00:00'));

array

Two creation methods

  • Use literal quantity
var arr = [1,2,3];
  • Using new Array()
var arr = new Array();//An empty array was created
var arr = new Array(3);//Created an array with a length of 3, which contains three empty array elements
var arr = new Array(2,3);//Created an array with elements 2 and 3

Detect whether it is an array

  • instanceof operator, which can judge whether an object belongs to a certain type
  • Array.isArray() is used to determine whether an object is an Array.isArray() is a method provided in HTML5
// Detect whether it is an array
// (1)instanceof operator
var arr = [];
var obj = {};
console.log(arr instanceof Array);//Return true
console.log(obj instanceof Array);//Return false
//Array. Isarray (parameter) H5 new method
console.log(Array.isArray(1,2,3));//false
console.log(Array.isArray([1,2,3]));//true
console.log(Array.isArray(obj));//false


function reverse(arr) {
    if (arr instanceof Array) {
        var newArray = [];
        for (var i = arr.length - 1; i >= 0; i--) {
            newArray[newArray.length] = arr[i];
        }
        return newArray;
    } else {
        return 'Please enter an array format such as[1,2,3]';
    }
}

Add or remove array elements

Method nameexplainReturn value
Push (parameter 1...)Add one or more elements at the end and pay attention to modifying the original arrayAnd returns the new length
pop()Delete the last element of the array, reduce the length of the array by 1, and modify the original array without parametersReturns the value of the element it deleted
Unshift (parameter 1...)Add one or more elements to the beginning of the array. Pay attention to modifying the original arrayAnd returns the new length
shift()Delete the first element of the array, reduce the length of the array by 1, and modify the original array without parametersAnd returns the value of the first element
// Add or remove array elements
//  1. Add element after push()
var arr = [1, 2, 3];
// arr.push(4,5)
console.log(arr.push(4, 5));//Return length 5
console.log(arr);//Return to [1,2,3,4,5]
// 2. Add element before unshift()
// arr.unshift(-1,0);
console.log(arr.unshift(-1, 0));//Return length 7
console.log(arr);//[-1, 0, 1, 2, 3, 4, 5]
// 3.pop() deletes the last element, reduces its length by 1, and returns the element
console.log(arr.pop());
// 4.shift() deletes the first element, reduces its length by 1, and returns the element
console.log(arr.shift());

Case (filter array)

There is an array [1500120020021001800] containing wages. It is required to delete more than 2000 of them and put the rest into the new array

var arr = [1500, 1200, 2000, 2100, 1800];
var newArray = [];
for (var i = 0; i <= arr.length - 1; i++) {
    if (arr[i] < 2000) {
        // newArray[newArray.length] = arr[i];
        newArray.push(arr[i]);
    }
}
console.log(newArray);

Array sorting

Method nameexplainModify original array
reverse()In the array, no parametersChange the original array and return the new array
sort()Sort the arrayChange the original array and return the new array
// 1. Invert array
var arr = [1, 2, 3];
arr.reverse()
console.log(arr);
// 2. Array sorting (bubble sorting)
var arr1 = [3, 4, 7, 1];
arr1.sort();
console.log(arr1);//[1,3,4,7]

//Pay attention to bug s
var arr2 = [1, 13, 4, 7, 77];
arr2.sort();
console.log(arr2);//[1, 13, 4, 7, 77] row the leftmost digits first, put 1 and 13 together, 4,7
// terms of settlement
arr2.sort(function (a, b) {
    // return a - b; Ascending order
    return b-a;//Descending order
});
console.log(arr2);

Array index

Method nameexplainReturn value
indexOf()Finds the first index of a given element in an arrayReturns - 1 if the index number exists and - 1 if it does not exist
lastIndexOf()The index of the last in the arrayReturns - 1 if the index number exists and - 1 if it does not exist
var arr = [1,2,3,1,4,5,3,1,2];
console.log(arr.indexOf(1));//Return index number 0
console.log(arr.indexOf(100));//Return - 1
console.log(arr.lastIndexOf(1));//Return index number 7 (find the last 1 and return its index number)

Case (array de duplication important)

Array ['c', 'a', 'z', 'a', 'x', 'a', 'x', c ',' b '], removing duplicate elements

analysis:

  • Objective: select the non duplicate elements in the old array and put them into the new array. Only one duplicate element is retained and put them into the new array to be duplicated.

  • Core algorithm: we traverse the old array, and then take the old array element to query the new array. If the element has not appeared in the new array, we will add it, otherwise we will not add it.

  • How do we know that the element does not exist? Take advantage of the new array Indexof (array element): if the return is - 1, it means that there is no such element in the new array

function unique(arr) {
    var newArr = [];
    for (var i = 0; i <= arr.length - 1; i++) {
        if (newArr.indexOf(arr[i]) === -1){
            newArr.push(arr[i]);
        }
    }
    return newArr;
}
var arr=['c','a','z','a','x','a','x','c','b'];
console.log(unique(arr));

Convert array to string

Method nameexplainReturn value
toString()Convert the array into a string and separate each item with a commaReturns a string
join('separator ')Method is used to convert all elements in the array into a stringReturns a string
// 1.toString()
var arr =[1,2,3];
console.log(arr.toString());//1,2,3
// 2.join('separator ')
console.log(arr.join('|'));//1|2|3
console.log(arr.join('+'));//1+2+3
console.log(arr.join('-'));//1-2-3
console.log(arr.join('&'));//1&2&3

other

Method nameexplainReturn value
concat()Connecting two or more arrays does not affect the original arrayReturns a new array
slice()Array interception slice(begin,end)Returns a new array of intercepted items
splice()Array delete splice (starting from the first few, the number to be deleted)Returns a new array of deleted items. Note that this will affect the original array

character string

Basic package type

To facilitate the operation of basic data types, JavaScript also provides three special reference types: string, number and Boolean

Basic packing type is to wrap simple data types into complex data types, so that basic data types have properties and methods.

var str = 'psyduck ';
console.log(str.length);//Output 3
//Only objects have properties and methods, and complex data types have properties and methods
//Why does a simple data type have a length attribute?
//Basic packing type: packing simple data types into complex data types
//(1) Wrapping simple data types into complex data types
var temp = new String('psyduck ');
//(2) Give the value of the temporary variable to str
str = temp;
//(3) Destroy temp
temp = null;

Immutability of string

It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the address has changed and a new memory space has been opened up in the memory

Return position according to character

All methods of string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed

// str.indexOf('character to find ', [starting position])
var str = 'The spring breeze of reform is blowing all over the ground,Spring is coming';
console.log(str.indexOf('spring'));//Return 2
console.log(str.indexOf('spring',3));//Search back from index number 3 and return 8
//lastIndexOf() starts from the back and can also add a position

Case (return character position)

Find the position and number of occurrences of all o in the string 'abcoefoxyozzopp'

analysis:

  • Core algorithm: first find the location where the first o appears
  • Then, as long as the result returned by indexOf is not - 1, continue to look back
  • Because indexOf can only find the first one, the subsequent search uses the second parameter to add 1 to the current index to continue the search
// Find the location and number of occurrences of all o in the string 'abcoefoxyozopp'
var str = 'abcoefoxyozzopp';
var index = str.indexOf('o');
var num = 0;
while(index !== -1){
    console.log(index);
    num++;
    index = str.indexOf('o',index+1);
}
console.log('o The number of occurrences is'+num+'second');

Return characters according to position (emphasis)

Method nameexplainuse
charAt(index)Returns the character at the specified position (the index number of the index string)str.charAt(0)
charCodeAt(index)Gets the ASCII code (index index number) of the character at the specified positionstr.charCodeAt(0)
str[index]Gets the character at the specified positionHTML5 and IE8 + support are equivalent to charAt()
// 1.charAt(index) returns characters according to position
var str = 'andy';
console.log(str.charAt(3));//y
// Traverse all characters
for (var i = 0; i < str.length; i++) {
    console.log(str.charAt(i));
}
// 2.charCodeAt(index) returns the ASCII code of the character. Purpose: to judge which key the user pressed
console.log(str.charCodeAt(0));//97,a corresponds to 97
// 3.str[index] H5 NEW
console.log(str[0]);//a

Case (Statistics of the most frequently occurring characters)

Judge the character that appears the most times in a string 'abcoefoxyozzopp', and count its times

analysis:

  • Core algorithm: use charAt() to traverse this string
  • Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be + 1
  • Traverse the object to get the maximum value and the character
// Prerequisite knowledge
// var o = {
//     age: 0
// }
// if (o['age'] != undefined) {
//     console.log('with this attribute ');
// } else {
//     console.log('No such attribute ');
// }
var str = 'abcoefoxyozzopp';
var o = {};
for (var i = 0; i < str.length; i++) {
    var chars = str.charAt(i);
    if (o[chars] != undefined) {//Chars does not add '' because it is a variable, and adding it will become finding chars
        o[chars]++;
    } else {
        o[chars] = 1;
    }
}
console.log(o);
var max = 0;
var ch = '';
for (var k in o) {
    //k gets the attribute name
    if (o[k] > max) {
        max = o[k];
        ch = k;
    }
}
console.log(max);
console.log(ch);

String operation method (emphasis)

Method nameexplain
concat(str1,str2,str3...)The concat() method is used to connect two or more strings. Splice string, equivalent to +, + is more commonly used
substr(start,length)Start from the start position (index number), and take the number of length. Remember this
slice(start,end)Start from the start position and intercept to the end position, but end cannot (both of them are index numbers)
substring(start,end)Start from the start position and intercept to the end position. The end cannot get the same value as slice, but it does not accept negative values
 // 1.concat()
 var str = 'andy';
 console.log(str.concat('kedaya'));//andykedaya
 // 2. Substr (start position, intercept several characters)
 var str1 = 'The spring breeze of reform is blowing all over the ground';
 console.log(str1.substr(2,2));//spring breeze

Other methods

// 1. The replacement string replace('replaced character ',' replaced character ') will only replace the first word
var str = 'andyandy';
console.log(str.replace('a', 'b'));//bndyandy
// There is a string 'abcoefoxyozzopp' to replace all o with*
var str1 = 'abcoefoxyozzopp';
while (str1.indexOf('o') !== -1) {
    str1 = str1.replace('o', '*');
}
console.log(str1);
// 2. Convert characters into array split('separator '). Learn the opposite of join before
var str2 = '1,2,3';
console.log(str2.split(','));
var str3 = '1&2&3';
console.log(str3.split('&'));

Simple type and complex type

Simple types are also called basic data types or value types, and complex types are also called reference types.

  • Value type: simple data type / basic data type. During storage, the value itself is stored in the variable, so it is called value type
    string ,number,boolean,undefined,null
  • Reference type: complex data type. When stored, only the address (Reference) is stored in the variable, so it is called reference data type
    Objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc

null is an empty object (it is an error, but it has not been changed so far)

Stack and heap

Stack space allocation difference:

  1. Stack (operating system): the operating system automatically allocates and releases the parameter values of the stored function and the values of local variables. Its operation mode is similar to the stack in the data structure;
    Simple data types are stored in the stack
  2. Heap (operating system): it stores complex types (objects), which are generally allocated and released by the programmer. If the programmer does not release them, they are collected by the garbage collection mechanism.
    Complex data types are stored in the heap

Note: there is no concept of stack in JavaScript. It is easier to understand through stack

Simple type memory allocation

  • Value type (simple data type): string, number, boolean, undefined, null
  • The data of value type variables is directly stored in variables (stack space)

  • Reference type (complex data type): objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc
  • The address is stored in the reference type variable (stack space), and the real object instance is stored in the heap space

Simple data type parameters

The formal parameter of a function can also be regarded as a variable. When we pass a value type variable as a parameter to the formal parameter of a function, we actually copy the value of the variable in the stack space to the formal parameter. Then any modification to the formal parameter inside the method will not affect the external variable

Complex data type parameters

The formal parameter of a function can also be regarded as a variable. When we pass a reference type variable to the formal parameter, we actually copy the heap address saved by the variable in the stack space to the formal parameter. The formal parameter and the actual parameter actually save the same heap address, so we operate on the same object.

// Complex data type parameters
function Person(name) {
    this.name = name;
}

function f1(x) { // x = p
    console.log(x.name); // 2. What is this output? Lau Andy   
    x.name = "Xue You Zhang";
    console.log(x.name); // 3. What is this output? Xue You Zhang
}
var p = new Person("Lau Andy");
console.log(p.name); // 1. What is this output? Lau Andy 
f1(p);
console.log(p.name); // 4. What is this output? Xue You Zhang

Keywords: Javascript Front-end

Added by Yossarian on Sat, 05 Feb 2022 20:17:28 +0200