[JavaScript] solid foundation of JS

preface

Considering that in the later development, we need to use a lot of js language for development, so we are going to reorganize the knowledge points of javascript and specially open a js column to review the js language. Everything is difficult at the beginning. If there is a problem in the back, you are welcome to face ruthlessly below!!!

data type

There are generally two types of data types in JavaScript, value type and reference type;

  • Value types: String, Number, Boolean, Null, Undefined, and Symbol

    The value type is stored by value, and the data is stored in the memory stack,

    Number, String, Boolean and symbol all correspond to a wrapper object, for example: new Number(5)
    This is also the principle that methods can be called with original data types:

    eg: ('happy').toString(),'happy' is a basic data type, and there is no toString method in itself, so it can be converted to an object by calling ToObject [spec] and then invoked in its package object new String('happy'). After the completion of the call, the wrapped object will disappear and the next need will be re created.

  • Reference type: Object, Array, Function

    The reference type is stored by reference. Instead of a value, it stores an address, and the data is stored in the memory heap

Common methods of data type detection

  • typeof is mainly used to detect original types
typeof 'seymoe'     // 'string'
typeof true         // 'boolean'
typeof 10           // 'number'
typeof Symbol()     // 'symbol'
typeof null         // 'object' cannot determine whether it is null
typeof undefined    // 'undefined'
typeof {}           // 'object'
typeof []           // 'object'
typeof(() => {})    // 'function'
  • instanceof is mainly used to detect custom objects
// Test whether the prototype of the constructor is on the prototype chain of the detected object obj
// prototype of obj instanceof constructor
[] instanceof Array// true
({}) instanceof Object// true
(()=>{}) instanceof Function// true
  • Object.prototype.toString.call is the ultimate method to judge the data type

    The essence of this method is to obtain the internal attribute [[Class]] of the object by relying on the Object.prototype.toString() method
    Passing in the original type can determine the result because the value is wrapped
    null and undefined can output results, which are handled by the internal implementation

// Object.prototype.toString.call(obj)
Object.prototype.toString.call({})              // '[object Object]'
Object.prototype.toString.call([])              // '[object Array]'
Object.prototype.toString.call(() => {})        // '[object Function]'
Object.prototype.toString.call('seymoe')        // '[object String]'
Object.prototype.toString.call(1)               // '[object Number]'
Object.prototype.toString.call(true)            // '[object Boolean]'
Object.prototype.toString.call(Symbol())        // '[object Symbol]'
Object.prototype.toString.call(null)            // '[object Null]'
Object.prototype.toString.call(undefined)       // '[object Undefined]'
Object.prototype.toString.call(new Date())      // '[object Date]'
Object.prototype.toString.call(new Math())      // '[object Math]'
Object.prototype.toString.call(new Set())       // '[object Set]'
Object.prototype.toString.call(new WeakSet())   // '[object WeakSet]'
Object.prototype.toString.call(new Map())       // '[object Map]'
Object.prototype.toString.call(new WeakMap())   // '[object WeakMap]'

var, let and const

When I first used javascript, the one that var played was called an expert. At first, the let and const keywords provided after es6 came out felt that var was not easy to use, and I found it really fragrant after I actually used it!!! (≖ ᴗ≖) ✧ basically, var has been eliminated now.

  • var: the global scope (within the function) declares that there is variable promotion. It is easy to use and uncomfortable!

    The execution of javascript code is divided into two stages, the precompile stage and the runtime stage,

    In the precompile stage, the variable declaration will be promoted, which means that the variable declaration defined by var will be placed at the top of the code, and the variable assignment is carried out in the code runtime stage. You can understand the variable promotion during JS execution through the following examples.

    console.log(a);
    var a = 0;
    
    // Equivalent to
    var a = undefined;
    console.log(a);
    a = 0;

    Of course, in addition to variable promotion, function promotion is the same. If you are interested, you can try it yourself.

    function fun() {}  //  This declaration will lead to function promotion, so it can be called no matter where the declaration is, and it will not execute itself
    
    var foo = function(){}  //  This writing method will lead to variable promotion, but will not lead to function promotion. In this case, you must declare it before calling it
  • let: block level scope, which can be regarded as {} forming a block level scope

    First, let declared variables will not be promoted, that is, if you want to use a variable declared by let, you must declare the variable before use;

    In the for loop, let can be used to assign respective scopes to the variables in each loop, so that they do not affect each other.

    // There is no variable promotion
    console.log(a);  // a is not defined.
    let a = 1;
    
    // Block level scope
    let b = 1; 
    {
       console.log(b) // 1 variables declared outside the scope can be accessed within the scope
       let c = 1;
    }
    console.log(c) // c is not defined. Variables declared within the scope cannot be accessed outside the scope
  • const: block level scope

    Like the let keyword, it forms a block level scope, but const is usually used to declare a constant!

    For stack storage type data, it cannot be changed after assignment through const declaration;

    For heap storage type data, the heap reference address cannot be changed after assignment through const declaration, but the data corresponding to the heap address can be changed (such as object properties, array options, etc.)

String API

str.split('-')   //Press - to split the string and return an array
str.substr(startIndex , count)    //Returns the intercepted new string 
str.substring(startIndex , endIndex)     //Returns a new string (including startIndex but excluding endIndex)
str.slice(startIndex , endIndex)     //Returns a new string (including startIndex but excluding endIndex)
str.repalce(Old string , New string)     //Replace string
str.toLowerCase()     //Turn lowercase
str.toUpperCase()     //Capitalize
str.trim()     //Remove spaces at both ends
str.charAt ( index )     //Returns the character of the index position
str.concat ( str1 , str2 , ...)   //Returns the spliced new string
str.indexOf (str1 , startIndex)    //The location index of str1 is returned, but - 1 is not returned
str.lastIndexOf ( str1 )   //Find the location index of str1 from back to front, but - 1 is not returned

Digital API

Math.abs(x)   //Returns the absolute value of x.
Math.ceil(x)   //Returns x, rounded up to the nearest integer.
Math.floor(x)   //Returns x, rounded down to the nearest integer.
Math.max(x, y, z, ..., n)   //Returns the number with the largest value.
Math.min(x, y, z, ..., n)      //Returns the number with the smallest value.
Math.pow(x, y)   //Returns the y-power of x.
Math.random()   //Returns a random number between 0 and 1.
Math.round(x)   //Rounds x to the nearest integer.
Math.trunc(x)   //Returns the integer part of the number (x).

Array API

// splice changes the original array
array.splice(startIndex , deleteCount , item1,item2, ...)  // Generally used to delete elements (or replace (insert) elements)

// slice returns a new array
array.slice(?startIndex , ?endIndex)  // The intercepted array values are put into a new array (excluding the elements at the endIndex position)

// Includes: in ES7, judge whether the array contains the specified value
array.includes(elem,[startIndex]) 
// The difference from indexOf is that NaN can be found in includes, but indexOf cannot
[NaN].includes(NaN) // true
[NaN].indexOf(NaN) // -1

array.concat(array1 , array2 , ...)  // Combination returns a new array
array.push( item )  // Inserts the last position of the array and returns the new length of the array
array.pop()  // Delete the last element of the array and return the deleted element value
array.shift()  // Delete the first element of the array and return the deleted element value
array.unshift( item )  // Inserts a new element before the first element of the array and returns the length of the new array
array.join('-')  // Use - to piece up each item of the array into a string and return the patched string
// array.join()  array.toString()
array.reverse()  // Invert the array and return
array.sort(function(a, b) { return a-b;})  // Sort (ascending)

// Loop traversal
array.forEach(function(value){})
array.forEach(function(value,index,newArray){})

// Map traverses each item of the array, inserts all the executed results into a new array and returns
array.map(function(value){
  return value*2;
})  

// Filter returns a new array of qualified values
array.filter(function(value){
  return value>3;
})

// Every returns true/false (true will be returned only if each item of the array meets the conditions) [the traversal will stop when the result is determined]
array.every(function(value){
  return value>0;
})

// Some returns true/false (as long as one item in the array meets the condition, it will return true) [the traversal will stop when the result is determined]
array.some(function(value){
  return value>0;
})

// indexOf() returns the location index of the first element from the front to the back of the lookup element
var index = ['tang','fu','qiang','fu'].indexOf('fu'); // index is 1;
// lastIndexOf() returns the first element position index from the back to the front of the lookup element
var lastIndex = ['tang','fu','qiang','fu'].lastIndexOf('fu'); // lastIndex is 3

// The Array.from method converts the two types of objects into a real array.
// Objects similar to arrays and iteratable objects (including the data structures Set and map in ES6)
Array.from(new FormData(from))

Object API

Object.keys(obj)  // Method returns an array of enumerable attributes of a given object
    var arr = ['a', 'b', 'c'];
  console.log(Object.keys(arr));       --- ['0', '1', '2']

  var obj = { 0: 'a', 1: 'b', 2: 'c' };
  console.log(Object.keys(obj));  // console: ['0', '1', '2']

    var anObj = { 100: 'a', 2: 'b', 7: 'c' };
    console.log(Object.keys(anObj));  // console: ['2', '7', '100']

Object.assign()  // Method is used to copy the values of all enumerable properties from one or more source objects to the target object. It will return the target object. eg: Object.assign(target, ...sources)

Object.getPrototypeOf(obj)  // Returns the Prototype of the specified object (the value of the internal [[Prototype]] attribute)
obj.hasOwnProperty(prop)  // Returns a Boolean value indicating whether the object has the specified property in its own properties.
Object.create(Create a prototype of an object , {Object's own enumerable properties(Optional)} ) // eg: Object.create(Array.prototype)
Object.defineProperty(Obj, prop, descriptor) // Returns the modified object
  descriptor: 
          value: default undefined,The value corresponding to this attribute can be any finite value JavaScript Value,(Functions, numbers, objects, etc)
            writable: default false,Set to true Time value Can be changed by the assignment operator
          configurable: Default to false Non modifiable, set to true This attribute can be modified or deleted
      enumerable: Default to false,Set to true This property can only appear in the enumeration property of the object
            
//Loop traversal:
// for in: during traversal, you can read not only the member property of the object itself, but also the prototype property of the object on the prototype chain. Therefore, you can use hasOwnProperty to judge whether a property is a property on itself. Returning true means that the property is a member property of the object, not a prototype property
for(key in obj){
  if(obj.hasOwnProperty(key)){
    object[key] = 1;
  }   
}

// for of: a unified method of traversing all data institutions
// As long as a data structure deploys the Symbol.iterator attribute, it is regarded as having an iterator interface. You can use for...of to traverse its members, that is, the Symbol.iterator method of the data structure is called inside the for...of loop

Date API

const myDate = new Date([params]); // params can take values (month 0 ~ 11): empty 2019,9,20 '2019 / 9 / 20', '2019-9-20', '2019-9-20 17:27:30'  

myDate.getYear();                           //Get current year (2 digits)
myDate.getFullYear();                       //Get the complete year (4 digits, 1970 -????)
myDate.getMonth();                          //Get the current month (0-11,0 represents January)
myDate.getDate();                           //Get current day (1-31)
myDate.getDay();                            //Get the current week X(0-6,0 for Sunday)
myDate.getTime();                           //Get the current time (milliseconds since 1970.1.1)
myDate.getHours();                          //Get current hours (0-23)
myDate.getMinutes();                        //Get current minutes (0-59)
myDate.getSeconds();                        //Get current seconds (0-59)
myDate.getMilliseconds();                   //Gets the current number of milliseconds (0-999)
myDate.toLocaleDateString();                //Get current date
myDate.toLocaleTimeString();                //Get current time
myDate.toLocaleString( );                   //Get date and time

summary

The above is a part of the summary of the basics of javascript. There are still a lot of contents about the basics of javascript, which will not be introduced in detail here. Next, let's talk about the Event Loop of JS. Interested partners can pay attention to it. If you want to know what you want to know, you can also comment below. If there are errors in the above contents, you can also leave a message to inform yourself. ヽ( ̄▽ ̄)ノ

Tags: Javascript

Posted on Mon, 08 Nov 2021 04:33:29 -0500 by xgrewellx