看代码说输出
var obj = { '2': 3, '3': 4, 'length': 2, 'splice': Array.prototype.splice, 'push': Array.prototype.push}obj.push(1)obj.push(2)console.log(11111, obj)
var obj = { '2': 3, '3': 4, 'length': 2, 'splice': Array.prototype.splice, 'push': Array.prototype.push}obj.push(1)obj.push(2)console.log(11111, obj)
var a = 1;(function(a) { console.log(1111,a) var a = 2; console.log(22222,a) })(a)console.log(a)
var a = 1;function printA(){ console.log(this.a);}var obj={ a:2, foo:printA, bar:function(){ printA(); }}obj.foo(); obj.bar(); var foo = obj.foo;foo();
var a=3; function c(){ alert(a); } (function(){ var a=4; c(); })();
async function async1() { console.log('async1 start'); // 2 await async2(); console.log('async1 end'); // 7 }async function async2() { new Promise(function (resolve) { console.log('promise1'); // 3 resolve(); }).then(function () { console.log('promise2'); // 6 });}console.log('script start'); // 1setTimeout(function () { console.log('setTimeout');// 9}, 0)setTimeout(function () { console.log('setTimeout');// 9}, 1000)async1();new Promise(function (resolve) { console.log('promise3'); // 4 resolve();}).then(function () { console.log('promise4'); //8});console.log('script end');// 5
export default class Index extends React.Component { constructor(props) { super(props); this.state = { val: 0 }; } componentDidMount() { this.setState({ val: this.state.val + 1 }); console.log('第一次 ', this.state.val); this.setState({ val: this.state.val + 1 }); console.log('第二次 ', this.state.val); setTimeout(() => { console.log('第三次 ', this.state.val); this.setState({ val: this.state.val + 1 }); console.log('第四次 ', this.state.val); this.setState({ val: this.state.val + 1 }); console.log('第五次 ', this.state.val); }, 0); } render() { return ( <div> {this.state.val} </div> ); }}
function Foo(){
Foo.a = function(){
console.log(1);
}
this.a = function(){
console.log(2)
}
}
Foo.prototype.a = function(){
console.log(3);
}
Foo.a = function(){
console.log(4);
}
Foo.a();
let obj = new Foo();
obj.a();
Foo.a();
function Person(name) {
this.name = name
}
var p2 = new Person('king');
console.log(p2.__proto__) //Person.prototype
console.log(p2.__proto__.__proto__) //Object.prototype
console.log(p2.__proto__.__proto__.__proto__) // null
console.log(p2.__proto__.__proto__.__proto__.__proto__)//null后面没有了,报错
console.log(p2.__proto__.__proto__.__proto__.__proto__.__proto__)//null后面没有了,报错
console.log(p2.constructor)//Person
console.log(p2.prototype)//undefined p2是实例,没有prototype属性
console.log(Person.constructor)//Function 一个空函数
console.log(Person.prototype)//打印出Person.prototype这个对象里所有的方法和属性
console.log(Person.prototype.constructor)//Person
console.log(Person.prototype.__proto__)// Object.prototype
console.log(Person.__proto__) //Function.prototype
console.log(Function.prototype.__proto__)//Object.prototype
console.log(Function.__proto__)//Function.prototype
console.log(Object.__proto__)//Function.prototype
console.log(Object.prototype.__proto__)//null
//css优先级
*{width:100px}
.img{width:400px;}
img[alt="img"] {width:300px}
img:hover{width:350px}
img{width:450px}
#img{width:250px;}
js手写题
//实现axios拦截器
function Axios (config) {
this.axios = config;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
}
}
// 发送请求
Axios.prototype.request = function (config) {
// 创建一个 promise 对象
let promise = Promise.resolve(config);
// 创建一个数组
const chains = [dispatchRequest, undefined];
// 处理拦截器
// 请求拦截器 将请求拦截器的回调 压入到 chains 的前面 request.handles = []
this.interceptors.request.handlers.forEach(item => {
chains.unshift(item.fulfilled, item.rejected);
});
// 响应拦截器
this.interceptors.response.handlers.forEach(item => {
chains.push(item.fulfilled, item.rejected);
});
// console.log(chains);
// 遍历
while (chains.length > 0) {
promise = promise.then(chains.shift(), chains.shift());
}
return promise;
}
// 发送请求
function dispatchRequest (config) {
// 返回一个 promise 队列
return new Promise((resolve, reject) => {
resolve({
status: 200,
statusText: 'OK'
});
});
}
// 创建实例
let context = new Axios({});
// 创建 axios 函数
let axios = Axios.prototype.request.bind(context);
//将 context 属性 config interceptors 添加至 axios 函数对象身上
Object.keys(context).forEach(key => {
axios[key] = context[key];
});
// 拦截器管理器构造函数
function InterceptorManager () {
this.handlers = [];
}
InterceptorManager.prototype.use = function (fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected
})
}
//以下为功能测试代码
// 设置请求拦截器 config 配置对象
axios.interceptors.request.use(function one(config) {
console.log('请求拦截器成功 1');
return config;
}, function (error) {
console.log('请求拦截器失败 1');
return Promise.reject(error);
});
axios.interceptors.request.use(function two(config) {
console.log('请求拦截器成功 2');
return config;
}, function (error) {
console.log('请求拦截器失败 2');
return Promise.reject(error);
});
// 设置响应拦截器
axios.interceptors.response.use(function (response) {
console.log('响应拦截器成功 1');
return response;
}, function (error) {
console.log('响应拦截器失败 1');
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
console.log('响应拦截器成功 2');
return response;
}, function (error) {
console.log('响应拦截器失败 2');
return Promise.reject(error);
});
// 发送请求
axios({
method: 'GET',
url: 'http://localhost:3000/posts'
}).then(response => {
console.log(response);
});
//防抖
function throttle(fn, delay) { let timer = null; return function() { let that = this; let args = arguments; if(timer) { clearTimeout(timer); } timer = setTimeout(function() { fn.apply(that, args); }, delay) }}// 节流function debounce(fn, delay) { let start = 0; return function() { let that = this, args = arguments; if(Date.now() - start > delay) { fn.apply(that, args); start = Date.now(); } }}
//实现promise.allfunction myAll(arr) { return new Promise((rs, rj) => { let count = 0; let result = []; if(arr.length === 0) return rs([]); arr.forEach((item, i) => { Promise.resolve(item).then((res) => { result[i] = res; // 按照输入顺序添加结果 count++; if(count === arr.length) { rs(result); } }).catch(() => { rj(err); }) }) })}
// 实现图片懒加载let img = document.getElementsByTagName('img');let len = img.length;let n = 0; // 标记执行到哪里window.onscroll = throttle(3000);function throttle(delay) { let timer = null; if(timer) clearTimeout(timer); timer = setTimeout(function() { lazyLoad(); }, delay)}function lazyLoad() { let c = document.documentElement.clientHeight || document.body.clientHeight; let s = document.documentElement.scrollTop || document.body.scrollTop; for(var i = n; i < img.length; i++) { if(img[i].offsetTop < c + s) { if(img[i].getAttribute('src') === 'default.png') { let url = img[i].getAttribute('data-src'); img[i].src = url; } n += 1; } }}
// 实现并发限制请求function Schedle() { this.list = []; this.limiRequest = 2; this.doneRequest = 0; this.add = (request) => { this.list.push(request) }; this.startTask = () => { for(let i = 0; i < this.limiRequest; i++) { request(); } } function request(){ this.doneRequest++; if(this.doneRequest <= this.limiRequest) { this.list.shift()().then((res) => { this.doneRequest--; this.request(); }) } }}let promise = (time, order) => { return new Promise((resolve, reject) => { setTimeout(function() { console.log(order) resolve(order) }, time) })}let schedle = new Schedle();let addTask = (time, order) => { schedle.add(promise(time, order))}addTask(1000, 2);addTask(2000, 1);addTask(500, 3);addTask(100, 4);schedle.startTask()
// 实现发布订阅模式EventBusclass EventBus{ constructor() { this.event = {}; } emit(e, ...args) { if(this.event[e]){ this.event[e].forEach(callback => callback(...args)); } } on(e, callback) { if(!this.event[e]) { this.event[e] = []; } this.event[e].push(callback); } off(e, callback) { let index = this.event[e] && this.event[e].findIndex(item => item === callback); if(index > -1) { this.event[e].splice(index, 1); } if(this.event[e].length === 0) { delete this.event[e]; } } offAll(e) { if(this.event[e]) { delete this.event[e]; } } // once方法}
//实现深拷贝 考虑全部类型
function checkType(any) { return Object.prototype.toString.call(any).slice(8, -1)// “[object function]” }function clone(any){ if(checkType(any) === 'Object') { // 拷贝对象 let o = {}; for(let key in any) { o[key] = clone(any[key]) } return o; } else if(checkType(any) === 'Array') { // 拷贝数组 var arr = [] for(let i = 0,leng = any.length;i<leng;i++) { arr[i] = clone(any[i]) } return arr; } else if(checkType(any) === 'Function') { // 拷贝函数 return new Function('return '+any.toString())() } else if(checkType(any) === 'Date') { // 拷贝日期 return new Date(any.valueOf()) } else if(checkType(any) === 'RegExp') { // 拷贝正则 return new RegExp(any) } else if(checkType(any) === 'Map') { // 拷贝Map 集合 let m = new Map() any.forEach((v,k)=>{ m.set(k, clone(v)) }) return m } else if(checkType(any) === 'Set') { // 拷贝Set 集合 let s = new Set() for(let val of any.values()) { s.add(clone(val)) } return s } return any; }
// 实现instanceoffunction fn(obj, fn) { if(!(obj && typeof obj === "object" || typeof obj === "function")) { return false; } var proto = Object.getPrototypeOf(obj); if(proto === fn.prototype) { return true; } else if(proto === null) { return false; } else { return fn(proto, fn); }}
// 数组扁平化 方法一function flatten(arr) { var result = []; for(var i of arr) { if(Array.isArray(i)) { result = result.concat(flatten(i)) } else { result.push(i); } } return result;}// 数组扁平化 方法二function flatten(arr) { return arr.reduce((prev, curr) => { return prev.concat(Array.isArray(curr) ? flatten(curr) : curr); }, [])}// 数组扁平化 方式三function flatten(arr) { return arr.toString().split('');}
var a = ?;if(a == 1 && a == 2 && a == 3){ console.log(1);}
算法题
// 无重复字符的最长子串 'abnsvvshu'function findStr(str) { if(!str) { return ''; } let result = []; let res = []; let max = 0; for(let i = 0; i < str.length; i++) { while(result.indexOf(str[i]) > -1) { result.shift(); } result.push(str[i]); max = Math.max(max, result.length); } return max;}
// 小孩报数function childNum(num, c) { let arr = []; for(var i = 0; i < num; i++) { arr[i] = i + 1; } let count = 0; // 当前报数 let index = 0; // 当前下标 let exitNum = 0; // 离开人数 while(exitNum < num - 1) { if(arr[index] !== 0) count++; if(count === c) { arr[index] = 0; exitNum += 1; }; index++; if(index === num) { index = 0; } } for(var i = 0; i < num; i++) { if(arr[i] !== 0) { return arr[i]; } }}
//两个数组的交集function intersection(nums1, nums2) { let set1 = new Set(nums1); let set2 = new Set(nums2); let result = new Set(); var find = (arr1, arr2) => { for(var i of arr1) { if(arr2.has(i)) { result.add(i) } } return [...result] } if(set1.size < set2.size) { return find(set1, set2); } else { return find(set2, set1); }}
//移动零var moveZeroes = function(nums) { let len = nums.length; let count = 0; for(let i = 0; i < nums.length;) { console.log(count, len) if(count === len) return; if(nums[i] === 0) { nums.splice(i, 1); nums.push(0); } else { i++; } count++; } return nums};
//翻转二叉树/二叉树的镜像function reverse(root) { if(!root) return null; let left = root.left && reverse(root.left); let right = root.right && reverse(root.right); root.left = right; root.right = left; return root;}
//有效的括号function isValid(str) { var result = []; for(var i of str) { if(['(', '{', '['].indexOf(str[i]) > -1) { result.push(str[i]); } if(str[i] === '}' && str[i] !== result[result.length - 1] || str[i] === ']' && str[i] !== result[result.length - 1] || str[i] === ')' && str[i] !== result[result.length - 1]) { result.pop(); } } return result.length === 0;}
// 循环打印红绿灯function fn(color, delay) { return new Promise((resolve, reject) => { setTimeout(function() { console.log(color) resolve(true) }, delay) })}function step() { fn('red', 2000).then((res) => { fn('green', 3000).then((res) => { fn('yellow', 2000).then((res) => [ step() ]) }) })}step()
// 每隔一秒打印1,2,3function fn(num) { for(let i = 0; i < num; i++) { setTimeout(() => { console.log(i) }, 1000 * i) }}function fn(num) { for(let i = 0; i < num; i++) { (function(i) { setTimeout(() => { console.log(i) }, 1000 * i) })(i) }}
// js将对象转换为tree// 转换前:const source = [{ id: 1, pid: 0, name: 'body' }, { id: 2, pid: 1, name: 'title' }, { id: 3, pid: 2, name: 'div' }]// 转换为: const tree = [{ id: 1, pid: 0, name: 'body', children: [{ id: 2, pid: 1, name: 'title', children: [{ id: 3, pid: 1, name: 'div' }] }] }]function changeTree(source) { source.forEach((item) => { if(item.pid) { source.forEach((curr) => { if(item.pid === curr.id) { if(!curr.children) { curr.children = []; } curr.children.push(item) } }) } }) return source.filter((item) => { return item.pid === 0 })}
// 二分查找function find(arr, target) { var left = 0, right = arr.length - 1; while(left <= right) { var middleIndex = Math.floor((left + right) / 2) if(arr[middleIndex] === target) { return middleIndex; } else if(arr[middleIndex] < target) { left = middleIndex + 1; } else { right = middleIndex - 1; } } return left;}
// 广度优先var levelOrder = function(root) { var result = []; var queue = []; if(root) queue.push(root); while(queue.length) { var curr = []; var len = queue.length; for(var i = 0; i < len; i++) { var node = queue.shift(); curr.push(node.val); if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); } result.push(curr) } return result};
//实现斐波那契
function feibo(target) { if(!target) return 0; if(target === 1 || target === 2) return 1; let a = 1, b = 1; for(let i = 2; i < target; i++) { [a, b] = [b, a + b]; } return b;}
//两数相加
function add(str1, str2) { var str1 = str1.split(''); var str2 = str2.split(''); var result = []; var r = str1.length - 1, l = str2.length - 1; var temp = 0; while(r >= 0 || l >= 0 || temp !== 0) { var first = 0, second = 0; if(str1[r]) { first = str1[r]; } if(str2[l]) { second = str[l]; } temp += first + second; if(temp >= 10) { temp = 1; result.unshift(temp % 10); } else { temp = 0; result.unshift(temp); } r--; l--; } return result.join('');}
// 数组第k大元素function quickSort(arr, k) { if(arr.length <= 1) { return arr[0]; } let left = [], right = []; let middleIndex = Math.floor(arr.length / 2); let middleVal = arr.splice(middleIndex, 1)[0]; for(var i = 0; i < arr.length; i++) { if(middleVal >= arr[i]) { left.push(arr[i]) } else { right.push(arr[i]) } } if(right.length === k - 1) { return middleValue; } else if (right.length < k - 1) { quickSort(left, k - 1 - right.length); } else { quickSort(right, k - 1); } return -1;}
// 洗牌算法function xipai(arr) { let len = arr.length; for(var i = 0; i < arr.length; i++) { let index = parseInt(Math.random() * len); let item = arr[index]; arr[index] = arr[i]; arr[i] = item; } return arr;}