JavaScript data types

Basic data type

NaN: Not a number Infinity Boolean: True,false or a type that can be implicitly converted to true or false

0, empty string, NULL,undinfed,NaN,false string: characters defined with ” or “”, or ”

Var str2= 'hello,${STR}' var str3= 'hello,${STR}' null:typeof null Object undefined: undefined: undefinedCopy the code

The difference between the null, and undefined: www.ruanyifeng.com/blog/2014/0… Symbol: new data type in ES6, defined using the Symbole() function to represent the uniqueness of the value of the defined variable

Reference data types (complex data types)

Object,Array,Function,RegExp,String

An object type can add properties to check whether an object is a property of the object itself: hasOwnProperty

for(var key in obj) {

if(obj.hasOwnProperty(key)) {

  console.log(obj[key]) }
Copy the code

}

2, Array: Array

Array methods stack methods: push() : add tail pop: delete tail unshift: add head shift: delete head splice: add, delete, and replace any part of the array

Arr. splice(2,0,' full stack 1909A') Arr.splice (4,2,' I'm going to ali ')Copy the code

The built-in array traversal method:

The forEach () : ForEach returns undeifned filter(): filters, iterates over the elements of the array that meet the condition, returns the new array map(): processes the original array to get a new array Reduce (): merges, FindIndex () finds the subindex find() finds every element in the array that matches every() returns true, Otherwise, false some() returns true as long as one of them is true. Otherwise, false includes() determines if the array contains a value. If yes, returns true, and if no, returns false

Flattening methods: 1. The toString implementation For example: var arr = [5,5,5,5, [2, 4, [2, (23, 5), 6], 7], 3,2,2,5] arr. The toString (). The split (', '). The map (item = > item * 1) 2. Function flatFn(arr) {var result=[]; if(! (arr instanceof Array)) return; for(var key in arr) { result=result.concat(Array.isArray(arr[key]) ? flatFn(arr[key]) : arr[key] ) } return result; } 3. Flat () //ES2019 publishing methodCopy the code

Array reference: developer.mozilla.org/zh-CN/docs/… ce

2. Class array:

What is a class array? Also known as pseudo array LikeArray, can only get the number by length, and specify a specific element by subscript, but can not use array API methods

Array-like usage scenarios: get the DOM collection, arguments,…

How to convert a class array to an array

1. Array. The from (Array) or […] class Array (2) Array. The prototype. Slice. Call (Array)

ES1.0 1997 ES2.0 1998 ES3.0 1999 ES4.0 failed ES5.0 2009 ES5.1 2011 ES6 2015. Since then, a new version has been released every year ES7 2016 ES8 2017……

The official ECMA Script repository can be updated at github.com/tc39/propos…

3. String: String

Trim () removes the left and right Spaces from the string

Don’t trim, you encapsulate a trim function trim (STR) {var reg = / ^ \ s + | \ s + $/ g return STR. Replace (reg, ‘ ‘)}

String.prototype.quchukongge=function() { var reg=/^\s+|\s+$/g return this.replace(reg,”) }

ToUpperCase () toUpperCase toLowerCase() toLowerCase substr() to take substring str.substr(start position, take several) substring(start substring, Split () turn the string to array join: turn the array to string slice(start subscript, end subscript) Turn the substring replace(find the string or match the re, replace the content) replace indexOf() find, return the subscript, Does not return -1 includes()

4. Math Object

Math.abs() : Take the absolute value

Math.random() Random value range: 0~~~~1

Return do any numeric range start-end range

Number = y – x + 1

X =10,y=20 11 num=y-x+1 Quantity =11 Start value: 10 Formula: math.floor (math.random ()* quantity)+ start value

// end: function randomIndex(start,end) {

var num=end-start+1
Copy the code

return Math.floor(Math.random()*num)+start }

Math.foor() is rounded down

Math.ceil() is rounded up

Math.round() to round

Math. Max () of great value

Var arr = 32,34,54,234,234,235,534,235,2] [23,3,34,23,24, –

Math.max.apply(Math,arr) Math.min.apply(Math,arr) Math.min.call(Math,… arr) Math.max.call(Math,… arr)

Math. Min (small) value

A. this b. this C. this D. this

Check whether it is a mobile terminal, if it is, jump to the mobile page

try {
  if (location.search.indexOf('? pc')! = =0 && /Android|Windows Phone|iPhone|iPod/i.test(navigator.userAgent)) {
    window.location.href = 'https://xw.qq.com?f=qqcom'; }}catch (e) {}
this*///1. Call this (window) directly
//console.log(this===window)

/* function Fn() { console.log('Fn:',this) //this.name='1909A' } //Fn()Copy the code

Var f1=new Fn(); //2.

//3. Functions belong to objects

/* var obj={ name:'1909A', Fn:function() { var hehe=function() { console.log('this===window:',this===window) console.log('this===obj:',this===obj) //console.log('this===Fn:',this===Fn) } hehe() } } obj.Fn(); * /
Copy the code
//4. This on the timer
/* var obj={ name:'1909A', Fn:function() { setTimeout(function() { console.log('this===window:',this===window) console.log('this===obj:',this===obj) },0) } } obj.Fn(); *Copy the code

/

/ / 5. DOM in this

var btn=document.querySelector('#btn')
btn.onclick=function() {
  // let _this=this;
   setTimeout(() = > {

        console.log(this===btn)
   },0)
Copy the code

}

Summary: : This is usually who calls, who this refers to, is it really so?

var name='ok'

var obj={
   name:'alice'.getName:function() {

     console.log(this.name)

  }
 
}

(false || obj.getName)()
Copy the code

Six, call, apply, bind

Call,apply, and bind are all used to change the point to this

The difference between:

The different refs

Call is passed as a comma-separated parameter

Call (target object, parameter 1, parameter 2… Parameters n)

Call (obj, obj, obj, obj, obj, obj)

The apply parameter is passed as an array

The function name. The apply (target, [parameters parameters 1, 2,… n]), for example: getName. Apply (obj, [‘ fifty and 11, 25, ‘Shanghai’])

Bind passes arguments in the form of commas

Getname.bind (obj,’ obj 11′,25,’ Shanghai ‘)() or getName.bind(obj)(‘ obj 11′,25,’ Shanghai ‘) is executed

Call getname.bind (obj)() call getname.bind (obj)()

Call implementation principle (do not call, their own manual simulation to achieve a call function)

Call is a function-based implementation that adds a temporary function to the target object, handles the assignment, receives the parameters, and then deletes the temporary function instantiating the object =newConstructor ()// The constructor is also called a class. A class can generate multiple instantiated objects

var f1=new Function(a)// In the constructor this===f1 is always equal
var p1=new Person() // This ===p1 is always equal
// Call simulation code:
Function.prototype.call2 = function (context) {
    // The target object
    context = context || window;

    //this=== the instantiated function, which is essentially an object

    // Add a temporary function to context
    context.fn = this;

    // Accept arguments to handle arguments
    console.log('arguments:'.arguments)
    var args = [];
    for (var i = 1; i < arguments.length; i++) {

       // ["arguments[0]", "arguments[1]", "arguments[2]"]
        args.push('arguments['+i+'] ')
       // args.push(arguments[i])
    }

     // Execute the context.fn() function by passing the arguments
     eval('context.fn(' + args + ') ')
    
    
    // Delete the temporary function
    delete context.fn

    
}
Copy the code

Apply principle Function. The prototype. Apply2 = Function (context, arr) {/ / target object context = context | | window;

// add a temporary function context.fn = this; // add a temporary function context.fn = this; if (! Arr) {context.fn()} else {var args = []; for (var i = 0; i < arr.length; i++) { // ["arguments[0]", "arguments[1]", "The arguments [2]"] args. Push (' arr [' + I + '] ') / / the args. Push (the arguments) [I]} / / the execution context. The refs fn eval () function (' context. The fn (' + + args } // Delete the temporary function delete context.fnCopy the code

}

Principle of BIND

var obj = {
    init: 1.add: function(a, b) {
        return a + b + this.init;
    }
}
obj.add(1.2); / / 4
 
var plus = obj.add;
plus(3.4); // NaN, because this. Init does not exist, where this refers to window/global
 
plus.call(obj, 3.4) / / 8
plus.apply(obj, [3.4]); // 8. The difference between apply and call is that the second argument is an array
plus.bind(obj, 3.4); // Return a function. This is one of the differences between bind and call/apply. Bind does not execute immediately
Copy the code

To sum up, simply use bind to change the point to this, and the difference between this and call/apply has a deferred effect

7. The realization principle of new

The characteristics of the new

  1. New a constructor that automatically reutrn an instantiated object
  2. The new completed instantiation object ____proto___ automatically points to the constructor’s prototype
  3. The new constructor passes arguments that are automatically assigned to the currently instantiated object

Eight, shake and throttling

If the concept

If no event is triggered within a fixed time, it will be triggered after the end of the fixed time. If the event is triggered within a fixed time, it will be triggered after the extended fixed time

// Use the timer to realize shaking
function debounce(func,wait) {
    var timer=null;
    return function() {
    // Save the currently invoked DOM object
     var _this=this;
     // Save the event object
     var args=arguments;
     clearTimeout(timer)
     timer=setTimeout(function() {
         func.apply(_this,args)
     },wait)
    }

}
Copy the code

Throttling concept:

Regardless of whether an event is triggered within a fixed time, it will be triggered at a fixed time

There are two ways to do this

The first is timestamp

// The timestamp version implements throttling
function throttle(func,wait) {
    // Define the initial time
    var oldTime=0;

    return function() {
        var _this=this;
        var args=arguments;

        // The current timestamp
        var newTime=+new Date(a);// The current time is subtracted from the old time. If the time is greater than the time specified in wait, it is triggered
        if(newTime-oldTime>wait) {
            // Execute the triggered function
            func.apply(_this,args)
            // Update the old timeoldTime=newTime; }}Copy the code

Second: timer

// The timestamp version implements throttling
function throttle(func,wait) {
    var timer=null;

    return function() {
        var _this=this;
        var args=arguments;
       if(! timer) { timer=setTimeout(function() {
                timer=null;
                func.apply(_this,args)
            },wait)
       }
    }
}
Copy the code

Of course, if you are not proficient in the above, you can use the current market mainstream tool library: Lodash already provides a comprehensive tool method

For details, please refer to the Lodash website: www.lodashjs.com/