1- Implement (5).add(3).minus(6) output 6
(function () {
function check(n) {
n = Number(n);
return isNaN(n) ? 0 : n;
}
function add(n) {
n = check(n);
return this + n;
}
function minus(n) {
n = check(n);
return this - n;
}
["add"."minus"].forEach((item) = > {
Number.prototype[item] = eval(item); }); }) ();console.log((5).add(3).minus(2));
Copy the code
2- Write your own each method
//
let arr = [10.20.30."aa".40],
obj = {};
Array.prototype.each = function (. arg) {
let arr = [];
if (arg[1]) {
for (let i = 0; i < this.length; i++) {
if (arg[0].call(arg[1].this[i]) == false) {
break;
}
arr.push(arg[0].call(arg[1].this[i])); }}else {
for (let i = 0; i < this.length; i++) {
if (arg[0] (this[i]) == false) {
break;
}
arr.push(arg[0] (this[i])); }}return arr;
};
arr = arr.each(function (item) {
if (isNaN(item)) {
return false;
}
return item * 10;
});
console.log(arr); //[100, 200, 300]
Copy the code
3- Reverses the case of the string
var str = "Hahaha hhhLLL";
str = str.replace(/[a-zA-Z]/g.(content) = > {
return content.toUpperCase() === content // If converted to uppercase equals the original character, the original character is uppercase
? content.toLowerCase()
: content.toUpperCase();
});
console.log(str);
Copy the code
4- Write the same function as indexof
(function () {
function myIndexOf(T) {
// let lenT = T.length,
// lenS = this.length,
// res = -1;
//if(lenT<lenS){
// for (let i = 0; i <= lenS - lenT; i++) {
// if (this.substr(i, lenT) === T) {
// res = i;
// break;
/ /}
// }
/ /}
// return res;
let reg = new RegExp(T);
res = reg.exec(this);
return res === null ? -1 : res.index;
}
String.prototype.myIndexOf = myIndexOf; }) ();let S = "zzzzsssssaaaaa",
T = "sa";
console.log(S.myIndexOf(T));
Copy the code
5- Properties of the object
var a = {},
b = { key: "123" },
c = { key: "456" };
a[b] = "b";
a[c] = "c";
console.log(a); //c
/* Because in an object's property, the object's property automatically calls the toString() method on the property's prototype to convert any object.toString =='[object object]' */
var a = {},
b = Symbol("123"),
c = Symbol("123");
a[b] = "b";
a[c] = "c";
console.log(a); //b
/* Symbol creates a unique */ value
var a = {},
b = "123",
c = 123;
a[b] = "b";
a[c] = "c";
console.log(a); //c
/* Because in the property of the object, the property of the object automatically calls the toString() method on the property stereotype to convert to a string, so here 123.toString() == '123'*/
Copy the code
6 – object
function Foo() {
Foo.a = function () {
console.log(1);
};
this.a = function () {
console.log(2);
};
}
// Set a property method on the prototype that is shared by the instance. Only the instance can use it
Foo.prototype.a = function () {
console.log(3);
};
// Set private property methods for Foo as if it were a normal object
Foo.a = function () {
console.log(4);
};
Foo.a(); / / 4
let obj = new Foo();
obj.a(); // 1 /2 /2 /2
Foo.a(); //1 If you have an instance, you can use the method in the instance
Copy the code
7- Regular validation places Spaces before and after words
let str = "No ha ha ha h ho, easy to borrow, easy to pay back",
reg = /\b[a-z]+\b/gi;
str = str.replace(reg, (value) = > {
return "" + value + "";
});
console.log(str);
Copy the code
8- Array flattening
// The array flattens and removes duplicates, resulting in an ascending, non-repeating array
/ / 1.
let arr = [[1.2.2], [3.4.5.5], [6.7[13.14[19.20]]].10];
// arr = [...new Set(arr.flat(Infinity).sort((a, b) => a - b))];
/ / 2.
// arr = [
/ /... new Set(
// arr
// .toString()
// .split(",")
// .map((item) => Number(item))
// .sort((a, b) => a - b)
/ /),
// ];
// console.log(arr);
/ / 3.
// arr = [
/ /... new Set(
// JSON.stringify(arr)
// .replace(/(\[|\])/g, "")
// .split(",")
// .map((item) => Number(item))
// .sort((a, b) => a - b)
/ /),
// ];
// console.log(arr);
/ / 4.
// while (arr.some((item) => Array.isArray(item))) {
// arr = [].concat(... arr);
// }
// console.log(arr);
/ / 5.~ (function () {
function myFlat() {
let result = [],
fn = (arr) = > {
for (let index = 0; index < arr.length; index++) {
let item = arr[index];
if (Array.isArray(item)) {
fn(item);
continue;
} else{ result.push(item); }}}; fn(this);
return result;
}
Array.prototype.myFlat = myFlat; }) (); arr = arr.myFlat();console.log(arr);
Copy the code
9 – since writing new
/* What happens when a new instance is created? + Creates a private scope like normal function execution - parameter assignment - variable promotion + creates an object by default and lets this execute the object, which is an instance of the current class + code execution + returns the created object */ by default
function Dog(name) {
this.name = name;
}
function _new(Fn, ... arg) {
/ / 1.
// Create an empty object with its prototype chain pointing to Fn. Prototype (as an instance of Fn)
// let obj = {};
// obj.__proto__ = Fn.prototype;
/ / 2.
let obj = Object.create(Fn.prototype); Fn.call(obj, ... arg);return obj;
}
Dog.prototype.saHi = function () {
console.log("hi");
};
let sanmao = _new(Dog, "SAN MAO");
sanmao.saHi();
Copy the code
10- Merge arrays
let arr1 = ["A1"."A2"."B1"."B2"."C1"."C3"."D1"];
let arr2 = ["A"."B"."C"];
/ / to realize the combined array [" A1 ", "A1", "A", "B1" and "B2", "B", "C1", "C2", "C", "D1"]
// arr2 = arr2.map((item) => item + "Z");
// arr1 = arr1
// .concat(arr2)
// .sort((a, b) => a.localeCompare(b))
// .map((item) => item.replace("Z", ""));
// console.log(arr1);
let index = null;
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if(arr1[j].includes(arr2[i])) { index = j; }}if(index ! =null) {
arr1.splice(index + 1.0, arr2[i]);
index = null; }}console.log(arr1);
Copy the code
11- For and timer
// Since variables defined using var have no block-level scope. The for loop completes before the timer created in the for loop starts,
// Print I to call global I, I =10;
/*for (var i = 0; i < 10; i++) { setTimeout(() => { console.log(i); }, 100); } * /
// Closure resolution
// for (var i = 0; i < 10; i++) {
// ~(function (i) {
// setTimeout(() => {
// console.log(i);
/ /}, 1000);
// })(i);
// }
// for (var i = 0; i < 10; i++) {
// // ~(function (i) {
// // setTimeout(() => {
// // console.log(i);
/ / / /}, 1000);
// // })(i);
// setTimeout(
// ((i) => {
// return () => {
// console.log(i);
/ /};
// })(i),
/ / 1000
/ /);
// }
// Use the bind mechanism to pass the output of the function each time it executes through the loop
var fn = function (i) {
console.log(i);
};
for (var i = 0; i < 10; i++) {
setTimeout(fn.bind(null, i), 1000);
}
Copy the code
12- Name anonymous functions
// let fn = function AAA() {
// console.log(AAA);
// };
// fn();
// function fn() {
// console.log(fn);
// }
// console.log(fn);
var b = 10;
(function b() {
var b = 20;
console.log(b); / / 20}) ();console.log(b); / / 10
var c = 10;
(function c() {
c = 20;
console.log(c); C / / function}) ();console.log(c); / / 10
Copy the code
13-== Indicates the comparison operation
/* == if the left and right data types are different, convert them to the same data type and then compare them. Null === undefined null== =undefined 3. NaN is not equal to anyone, including NaN. ToString (); toString(); toString(); All other cases are converted to numbers for comparison purposes (if the data type is different) */
// console.log({} == {});
// console.log(null == undefined);
// console.log(NaN == NaN);
// console.log([1] == "1");
// console.log([1] == true);
// var a = {
// n: 0,
// toString() {
// return ++this.n;
/ /},
// };
var a = [1.2.3];
a.toString = a.shift; // Make its toString method change and call its own private method
if (a == 1 && a == 2 && a == 3) {
console.log(123);
}
Copy the code
15-push
let obj = {
2: 3.3: 4.length: 2.push: Array.prototype.push,
};
obj.push(1);
obj.push(2);
console.log(obj);
// What happens when array.prototype. push is implemented
/* Array.prototype.push = function (val) { this[this.length] = val; return this.length; }; * /
/* This [this.length] = 1; /* This [this.length] = 1; Let obj = {2: 1, 3: 2, length: 4, push: array.prototype push,}; * /
Copy the code
16- Bubble sort
/* Bubble sort idea: compare the current item to the next item in the array, and place the larger item after. At least leng-1 round comparison should be carried out, each round of comparison will be the largest, the second largest, the second three.. Put the value of. In the first round, the maximum number of comparisons is leng-1. In the second round, the maximum number of comparisons is leng-2. In the third round, the maximum number of comparisons is leng-3 * /
let arr = [12.8.24.16.1];
function bubble(arr) {
// let temp = 0;
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; }}}return arr;
}
bubble(arr);
Copy the code
17- Insertion sort
/* Insert sort (catch the sort of cards) first catch a card, then catch the second card, the second card and catch the card from the end of the comparison, in the encounter smaller than it is inserted in the back of this card */
function insertSort(arr) {
let array = [];
array.push(arr[0]);
for (let i = 1; i < arr.length; i++) {
for (let j = array.length - 1; j >= 0; j--) {
if (array[j] <= arr[i]) {
array.splice(j + 1.0, arr[i]);
break;
}
if (j === 0) { array.unshift(arr[i]); }}}console.log(array);
return array;
}
insertSort([13.8.12.1.16.0]);
Copy the code
18- Quicksort
/ * arr =,8,9,6,15,2 [24]; Quicksort takes the middle value and then strips it out in arR and compares the rest of the values against the middle value. Assume that the middle value is 9 and puts those smaller than 9 in the left array and those larger than 9 in the right array. [24,15] then take the middle value of the left and right array, divide the left and right array and so on until the last number is left, and then splice the left and right array with the middle number */
function quickSort(arr) {
//4. End recursion when arR is less than or equal to one term
if (arr.length <= 1) {
return arr;
}
//1. Find the middle item in the array and remove it from the original array
let middleIndex = Math.floor(arr.length / 2);
let middleValue = arr.splice(middleIndex, 1) [0];
//2. Prepare the left and right arrays and loop through each item of the array
let left = [],
right = [];
for (let i = 0; i < arr.length; i++) {
arr[i] > middleValue ? right.push(arr[i]) : left.push(arr[i]);
}
//3. Recursion keeps the left and right arrays doing this until the left and right arrays are sorted. (Finally make left + center + right)
return quickSort(left).concat(middleValue, quickSort(right));
}
console.log(quickSort([24.8.9.6.15.2]));
Copy the code
19- Object variable group
Let obj = {1: 222, 2: 123, 5: 888,}; Turn it into the following structures [888, 222123, null, null, null, null, null, null, null, null] * /
let obj = {
1: 222.2: 123.5: 888};/ / 1.
// let arr = new Array(12).fill(null).map((item, index) => {
// return obj[index + 1] || null;
// });
/ / 2.
obj.length = 13;
let arr = Array.from(obj).slice(1);
console.log(arr);
arr = arr.map((item) = > (item == undefined ? null : item));
console.log(arr);
Copy the code
20- Rotate the array
/* rotate array given an array, move the elements of the array k positions to the right, where k is non-negative input :[1,2,3,4,5,6] k=3 output :[5,6,7,1,2,3,4] */
function rotate(arr, k) {
if (k < 0 || k === 0 || k === arr.length) return arr;
if (k > arr.length) k = k % arr.length;
// for (let i = 0; i < k; i++) {
// arr.unshift(arr.pop());
// }
return arr.splice(arr.length - k).concat(arr);
}
console.log(rotate([1.2.3.4.5.6.7].3));
Copy the code
21- Implement the add function
/* Implement the add function to satisfy the following functions add(1); //1 add(1)(2); //3 add(1)(2)(3); / / add 6 (1) (2, 3); / / 6 add (1, 2) (3); / / 6 add (1, 2, 3); //6 functions: the idea of pre-processing (using closure mechanisms) */
/ / handwritten bind
// ~(function () {
// function myBind(context = window, ... outerArg) {
// let _this = this;
// return function (... innerArg) {
// _this.call(context, ... outerArg.concat(innerArg));
/ /};
/ /}
// Function.prototype.myBind = myBind;
/ /}) ();
// // Using the preservation function of closure, Keshi pre-preservation ideas
// function fn(x) {
// return function (y) {
// return x + y;
/ /};
// }
// console.log(fn(100)(200));
function currying(fn, length) {
length = length || fn.length;
return function (. arg) {
if (arg.length >= length) {
returnfn(... arg); }return currying(fn.bind(null. arg), length - arg.length); }; }// add = currying(add, 4);
let add = currying((. arg) = > eval(arg.join("+")), 4);
// console.log(add(1));
console.log(add(1) (2) (3) (4));
// console.log(add(1, 2)(3, 4));
// add(1);
// add(1)(2)(3)(4);
Copy the code