functionmyInstanceof(left, right) { let proto = Object.getPrototypeOf(left), prototype = right.prototype; while (true) { if (!proto) returnfalse; if (proto === prototype) returntrue; proto = Object.getPrototypeOf(proto); } }
3. 手写 new 操作符
1 2 3 4 5 6 7 8 9 10 11 12
functionnewOperator(ctor, ...args) { if(typeof ctor !== 'function'){ throw'newOperator function the first param must be a function'; } let obj = Object.create(ctor.prototype); let res = ctor.apply(obj, args);
// 如果构造函数的返回值 res 是一个对象或函数,则直接返回它。否则,返回新创建的对象 obj let isObject = (typeof res === 'object' && res !== null); let isFunction = (typeof res === 'function'); return (isObect || isFunction ) ? res : obj; };
Promise.all = function(promises) { returnnewPromise((resolve, reject) => { if(!Array.isArray(promises)) thrownewTypeError(`promises must be a array`) let result = []; let index = 0; let len = promises.length; if(len === 0) { resolve(result); return; }
// 简便写法 Array.prototype.push = function() { for( let i = 0 ; i < arguments.length ; i++){ this[this.length] = arguments[i] ; } returnthis.length; }
Array.prototype.push = function(...items) { let O = Object(this); let len = this.length >>> 0; let argCount = items.length >>> 0; // 2 ** 53 - 1 为JS能表示的最大正整数 if (len + argCount > 2 ** 53 - 1) { thrownewTypeError("The number of array is over the max value restricted!") } for(let i = 0; i < argCount; i++) { O[len + i] = items[i]; } let newLength = len + argCount; O.length = newLength; return newLength; }
pop
1 2 3 4 5 6 7 8 9 10 11 12 13
Array.prototype.pop = function() { let O = Object(this); let len = this.length >>> 0; if (len === 0) { O.length = 0; returnundefined; } len --; let value = O[len]; delete O[len]; O.length = len; return value; }
filter
1 2 3 4 5 6 7 8 9 10
Array.prototype._filter = function(fn) { if (typeof fn !== "function") { throwError('参数必须是一个函数'); } const res = []; for (let i = 0, len = this.length; i < len; i++) { fn(this[i]) && res.push(this[i]); } return res; }
Array.prototype.reduce = function(callbackfn, initialValue) { // 异常处理,和 map 一样 if (this === null || this === undefined) { thrownewTypeError("Cannot read property 'reduce' of null or undefined"); } if (Object.prototype.toString.call(callbackfn) != "[object Function]") { //注意中间无逗号 thrownewTypeError(callbackfn + ' is not a function') } let k = 0; // 后面要重复利用 let O = Object(this); // 先将调用者转为对象 let len = O.length >>> 0; // 确认为整数 let accumulator = initialValue; // 积累值 if (accumulator === undefined) { // 没传初始值 for(; k < len ; k++) { if (k in O) { accumulator = O[k]; k++; break; } } } // 表示数组全为空 if(k === len && accumulator === undefined) thrownewError('Each element of the array is empty');
var quick_sort = function(a, l, r){ if(l >= r)return; let i = l - 1, j = r + 1; let mid = l + r >> 1; let x = a[mid]; while(i < j){ do i++; while(a[i] < x); do j--; while(a[j] > x); if(i < j){ let z = a[i]; a[i] = a[j]; a[j] = z; } } quick_sort(a, l, j); quick_sort(a, j + 1, r); } var q = [1,44,6,713,76]; quick_sort(q, 0, q.length-1); console.log(q); // [ 1, 6, 44, 76, 713 ]
splice 方法(了解原理)
代码
Array.prototype.splice = function(startIndex, deleteCount, ...addElements) {
// 1. 初始工作
let argumentsLen = arguments.length;
let array = Object(this);
let len = array.length;
let deleteArr = new Array(deleteCount);
// 删除数目没有传,默认删除startIndex及后面所有的 if (argumentsLen === 1) deleteCount = len - startIndex; else if (deleteCount < 0) deleteCount = 0 // 删除数目过小 else if (deleteCount > len - startIndex) deletCount = len - startIndex; //删除数目过大
// 3. 判断 sealed 对象和 frozen 对象, 即 密封对象 和 冻结对象
if (Object.isSealed(array) && deleteCount !== addElements.length) {
throw new TypeError('the object is a sealed object!')
} else if(Object.isFrozen(array) && (deleteCount > 0 || addElements.length > 0)) { throw new TypeError(‘the object is a frozen object!’) }
// 4.拷贝删除的元素 for (let i = 0; i < deleteCount; i++) { let index = startIndex + i; if (index in array) { let current = array[index]; deleteArr[i] = current; } }
letformat = n => { let num = n.toString() // 转成字符串 let decimals = '' // 判断是否有小数 num.indexOf('.') > -1 ? decimals = num.split('.')[1] : decimals let len = num.length if (len <= 3) { return num } else { let temp = '' let remainder = len % 3 decimals ? temp = '.' + decimals : temp if (remainder > 0) { // 不是3的整数倍 return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') + temp } else { // 是3的整数倍 return num.slice(0, len).match(/\d{3}/g).join(',') + temp } } } format(12323.33) // '12,323.33'
5. 手写日期格式化函数
1 2 3 4 5 6 7 8 9 10 11 12
constdateFormat = (dateInput, format)=>{ var day = dateInput.getDate() var month = dateInput.getMonth() + 1 var year = dateInput.getFullYear() format = format.replace(/yyyy/, year) format = format.replace(/MM/,month) format = format.replace(/dd/,day) return format } dateFormat(newDate('2020-12-01'), 'yyyy/MM/dd') // 2020/12/01 dateFormat(newDate('2020-04-01'), 'yyyy/MM/dd') // 2020/04/01 dateFormat(newDate('2020-04-01'), 'yyyy年MM月dd日') // 2020年04月01日
6. 实现大整数相加
来自算法篇章
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
let a = '13124342343353535235' let b = '34423434234234243233' // 两个字符串a, b let arr1 = a.split('').map(Number); let arr2 = b.split('').map(Number); let res = []; let flag = 0; while(arr1.length > 0 || arr2.length > 0) { let t1 = arr1.pop() || 0; // 判断arr1是否已经为空 let t2 = arr2.pop() || 0; // 判断arr2是否已经为空 let tmp = t1 + t2 + flag; flag = Math.floor(tmp / 10) res.unshift(tmp % 10) } if(flag) res.unshift(flag); res = res.join('') console.log(res); // 47547776577587778468