var和let const的区别
var是ES5语法,let,const是ES6语法
var,let用来定义变量,const用来定义常量
let ,const有块级作用域,var没有
typeof可以用来判断哪些类型
undefined,number,string,boolean,symbol
object(注意,typeof null==='object')
function
列举强制类型转换和隐式类型转换
强制类型转换:parseInt,parseFloat,toString等
隐式类型转换:if,逻辑运算,==,+拼接字符串
手写深度比较isEqual
function isObject(obj){
return typeof(obj)==='object'&&obj!==null
}
function isEqual(obj1,obj2){
if(!isObject(obj1)||!isObject(obj2)){
return obj1===obj2
}
if(obj1===obj2){
return true;
}
const obj1Keys=Object.keys(obj1);
const obj2Keys=Object.keys(obj2);
if(obj1Keys!=obj2Keys){
return false;
}else{
for(let key in obj1){
let res=isEqual(obj1[key],obj2[key]);
if(!res){
return false;}
}
}
return true;
}
数组API
pop:尾减
push:尾增
shift:头减
unshift:头增
slice:截取
splice:剪接
ajax请求get和post的区别
get一般用于查询操作,post一般用于提交操作
get参数拼接在url上,post放在请求体内
正则表达式
字符串 字母开头,后面字母数字下划线,长度6-30
const reg=/^[a-zA-Z]\w{5-29}$/
邮政编码
/\d{6}/
小写英文字母
/^[a-z]+$/
英文字母
/^[a-zA-Z]+$/
日期格式 2019-12-1
/^\d{4}-\d{1,2}-\d{1,2}/
用户名
/^[a-zA-Z]\w{5,17}$/
简单的IP地址匹配
/\d+\.\d+\.\d+\.\d+/
手写字符串trim
String.prototype.trim=function(){
return this.replace(/^\s+/,'').replace(/\s+$/,'');
}
JS如何捕获异常
try{
//todo
}
catch(ex){
console.error(ex);
}
finally{
//todo
}
什么是Json
json是一种数据格式,本质是一段字符串
json格式和js对象结构一致,对js语言更友好
window.JSON是一个全局对象,JSON.stringfy(对象转换JSON) JSON.parse(Json转换对象)
解析URL参数
function query(name){
const search=location.search;
const p=new URLSearchParams(search);
return p.getname(name);
}
将url参数解析为JS对象
function queryToObj(){
const res={}
const search=location.search.substr(1);
search.split('&').forEach(paramStr=>{
const arr=paramStr.split("=");
const key=arr[0];
const value=arr[1];
res[key]=value;
})
return res;
}
数组扁平化
function flatten(arr){
let res=[];
for(let i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
res.concat(flatten(arr[i]));}
else{res.push(arr[i]);} }
return res;
}
数组去重
function unique(arr){
let res=[];
arr.forEach(item=>{
if(res.indexof(item)==-1){
res.push(item);}});
return res;
}
function unique(arr){
let res=new Set(arr);
return [...res];}
手写深拷贝
function deepClone(obj){
if(typeof(obj)!=='object'||obj==null){
return obj;
}
let result;
if(obj instanceof Array){
result=[];
}
else{
result={};
}
for(let key in obj){
if(obj.hasOwnproperty(key)){
result[key]=deepClone(obj[key]);
}
}
return result;
}
requestAnimationFrame
//用settimeout来实现动画
const div1=$("#div1");
let curWidth=100;
let maxWidth=640;
function animate(){
curWidth=curWidth+3;
div1.css('width',curWidth);
if(curWidth<maxWidth){
setTimeOut(animate,16.7);
}
}
animate();
//使用requestAnimationFrame
const div1=$("#div1");
let curWidth=100;
let maxWidth=640;
function animate(){
curwidth=surWidth+3;
div1.css('width',curWidth);
if(curWidth<maxWidth){
window.requestAnimationFrame(animate);
}
}
animate();