preface

Programming is a very happy thing, to achieve a purpose, we can have a lot of methods and paths, in this article we introduce some JavaScript strange technology and craftiness, only for your reference, various gods in the usual code writing, such as a lot of simple and efficient writing; Feel free to leave your comments below.

First, data type detection

1.1 typeof

The typeof operator returns a string representing the typeof the unevaluated operand; The operator data type (returns a string, corresponding to the list shown)

1.2 instanceof

var str = "This is a simple string"; 
var num = 1111;
var boolean = true;
var und = undefined;
var nl = null;
var sb = Symbol('1111');
var obj = {}; // Non-primitive data literal definition

console.log(str instanceof String);         // false
console.log(num instanceof Number);         // false
console.log(boolean instanceof Boolean);    // false
console.log(nl instanceof Object);          // false
console.log(sb instanceof Symbol);          // false
console.log(obj instanceof Object);         // true

var strN = new String("This is a simple string");
var numN = new Number(1111);
var booleanN = new Boolean(true);
var objN = new Object(a);console.log(strN instanceof String);            // true
console.log(numN instanceof Number);            // true
console.log(booleanN instanceof Boolean);       // true
console.log(objN instanceof Object);            // true
Copy the code

The instanceof operator tests whether the constructor’s Prototype property appears anywhere in the object’s prototype chain; From the above result, the raw data type produced by the literal cannot be determined using instanceof.

1.3 the Object. The propotype. ToString

Object.prototype.toString.call('string');       //"[object String]"
Object.prototype.toString.call(1111);           //"[object Number]"
Object.prototype.toString.call(true);           //"[object Boolean]"
Object.prototype.toString.call(null);           //"[object Null]"
Object.prototype.toString.call(undefined);      //"[object Undefined]"
Object.prototype.toString.call(Symbol('111'));  //"[object Symbol]"
Object.prototype.toString.call({});             //"[object Object]"
Copy the code

The above method is the most convenient and effective

1.4 the constructor

Compares whether the constructor of an object is equal to that of a class

var a = {}
a.constructor === Object     // true

var b = '111';
b.constructor === String    // true

var strN = new String('11111');
strN.constructor === String // true

var c = true;
c.constructor === Boolean   // true

var d = Symbol('symbol')
d.constructor === Symbol    // true
Copy the code

1.5 propotype

Compare whether the stereotype of the object is equal to that of the constructor

var a = {}
a.__proto__ === Object.prototype     // true

var t = new Date(a); t.__proto__ ===Date.prototype      // true


var str = 'sting';
str.__proto__ === String.prototype  // true

var strN = new String('11111');
strN.__proto__ === String.prototype // true

Copy the code

2. Special operation of data

2.1 Exchange two values

2.1.1 Use a number xOR itself equal to 0 and xOR operation conforms to exchange rate

var a = 3;
var b = 4
a ^= b; // a = a ^ b
b ^= a;
a ^= b;

console.log(a, b);
Copy the code

2.1.2 Deconstructing assignments using ES6

let a = 1;
let b = 2;

[b, a] = [a, b];

console.log(a, b);
Copy the code

2.2 Rounding decimals

var num = 123.123

// Common methods
console.log(parseInt(num)); / / 123
// The "bitwise not" operator
console.log(~~ num); / / 123
/ / or by location
console.log(num | 0); / / 123
// Bitwise xOR
console.log(num ^ 0); / / 123
// Left-shift operator
console.log(num << 0); / / 123

Copy the code

2.3 Digital amount format in thousandths

2.3.1 use Number. The prototype. ToLocaleString ()

var num = 123455678;
var num1 = 123455678.12345;

var formatNum = num.toLocaleString('en-US');
var formatNum1 = num1.toLocaleString('en-US');

console.log(formatNum); / / 123455678
console.log(formatNum1); / / 123455678123
Copy the code

2.3.2 Using regular Expressions

var num = 123455678;
var num1 = 123455678.12345;

var formatNum = String(num).replace(/\B(? =(\d{3})+(? ! \d))/g.', ');
var formatNum1 = String(num1).replace(/\B(? =(\d{3})+(? ! \d))/g.', ');

console.log(formatNum); / / 123455678
console.log(formatNum1); // 123,455,678.12,345
Copy the code

Common operations on object data

3.1 Deep cloning techniques

  • 3.1.1 Json. stringify converts to characters, and json. parse regenerates the JSON data type
function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}
var obj = {
    number: 1.string: 'abc'.bool: true.undefined: undefined.null: null.symbol: Symbol('s'),
    arr: [1.2.3].date: new Date(),
    userInfo: {
        name: 'Better'.position: 'front-end engineer'.skill: ['React'.'Vue'.'Angular'.'Nodejs'.'mini programs']},func: function () {
        console.log('hello better'); }}console.log(deepClone(obj))
Copy the code

The following conclusions can be drawn from the printed results:

  1. The undefined, symbol, and function types are filtered out directly

  2. The date type is automatically converted to a string

  • 3.1.2 Common Methods Simple recursion
function deepClone(obj) {
    var newObj = obj instanceof Array ? [] : {};
    for (let i in obj) {
        newObj[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
    }
    return newObj;
}

var obj = {
    number: 1.string: 'abc'.bool: true.undefined: undefined.null: null.symbol: Symbol('s'),
    arr: [1.2.3].date: new Date(),
    userInfo: {
        name: 'Better'.position: 'front-end engineer'.skill: ['React'.'Vue'.'Angular'.'Nodejs'.'mini programs']},func: function () {
        console.log('hello better'); }}console.log(deepClone(obj))
Copy the code

From the printed results, there are a Number of problems with this implementation: this method can only implement deep copy of certain objects (such as objects, arrays, and functions), and cannot implement null and wrap copy of Number, String, Boolean, Date, and RegExp objects.

3.2 Object Traversal Mode

3.2.1 for -in

function A() {
	this.a = 1
	this.b = 1
}

A.prototype = {
	c: 1.d: 2
}

var a = new A()

for(var i in a) {
    console.log(i)
}
Copy the code

As can be seen from the printed results above, for-In traverses object attributes, including those in the prototype chain

3.2.2 Object. Entries ()

function A() {
	this.a = 1
	this.b = 1
}

A.prototype = {
	c: 1.d: 2
}

var a = new A()
var et = Object.entries(a)
console.log(et)
Copy the code

From the above results, Entries return an array of key-value pairs for a given object’s own enumerable properties

3.2.3 Object. The keys (), the Object. The values ()

function A() {
	this.a = 1
	this.b = 1
}

A.prototype = {
	c: 1.d: 2
}

var a = new A()
var keys = Object.keys(a)
var values = Object.values(a)
console.log(keys, values)
Copy the code

Keys and values return an array of the given object’s own enumerable property values

4, array common operations

4.1 Array deduplication

  • 4.4.1 Set to heavy
var arr = [1.2.1.1.22.4.5.6];
arr1 = [...new Set(arr)];
Copy the code
  • 4.1.2 Combine the array filter method with the indexOf() method
var arr = [1.2.3.2.6.'2'.3.1];
function uniqueArr (arr) {
    return arr.filter(function (ele, index, array) {
        // use the array indexOf() method to return the indexOf the first value found
        // If the index value of an array element is not equal to the value returned by the indexOf method, then the value is duplicated and filtered directly
        returnarray.indexOf(ele) === index; })}Copy the code

4.2 Multidimensional array a line of code to achieve one-dimensional conversion

var arr = [ [1.2.2], [3.4.5.5], [6.7.8.9[11.12[12.13[14]]]],10];

var resultArr = arr.toString().split(', ').map(Number);

console.log(resultArr); / / [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
Copy the code

4.3 a line of code to achieve the number of tags used to obtain a web page

[...new Set([...document.querySelectorAll(The '*')].map(node= > node.tagName))].length;
Copy the code

4.4 How can A == 1&&a == 2&&a == 3 be Realized

4.4.1 Rewriting the toString method of arrays

var a = [1.2.3];
// a.join = a.shift;
// a.valueOf = a.shift;
a.toString = a.shift;

console.log(a == 1 && a == 2 && a == 3); // true
Copy the code

How it works: Implicit conversions occur when complex type data is compared with primitive data, and the toString() or valueOf() methods are called

4.4.2 Overwriting the toString method of an object

var a = {
    value: 1.toString: function () {
        returna.value++; }}console.log(a == 1 && a == 2 && a == 3); // true
Copy the code

4.5 Counting the Number of Occurrences of the same Character in a String

var str = 'aaabbbccc66aabbc6';

var strInfo = str.split(' ').reduce((p, c) = > (p[c]++ || (p[c] = 1), p), {});

console.log(strInfo); // {6: 3, a: 5, b: 5, c: 4}
Copy the code

4.6 Converting an array-like object into an array

4.6.1 using Array. Prototype. Slice

var likeArrObj = {
    0: 1.1: 2.2: 3.length: 3
}

var arr1 = Array.prototype.slice.call(likeArrObj); // Or use [].slice.call(likeArrObj);
console.log(arr1); / / [1, 2, 3]
Copy the code

4.6.2 using Array. The from

var likeArrObj = {
    0: 1.1: 2.2: 3.length: 3
}

var arr = Array.from(likeArrObj);
console.log(arr); / / [1, 2, 3]
Copy the code

4.6.3 Using Object.values (omitted)